0

我正在使用hibernate开发一个学生信息系统,一个学生可以有多个课程(和分数)。我希望我的 POJO 像:

学生:student attributes + Set<Course>

课程:course attributes + int marks

但在数据库中,我关注了 3 个表。

create table STUDENT (
 STUDENT_ID BIGINT not null auto_increment primary key,
 // ... student type attributes
)

create table COURSE (
 COURSE_ID BIGINT not null auto_increment primary key,
 // ... course type attributes
)

create table STUDENT_COURSE_MARKS (
 STUDENT_ID BIGINT not null,
 COURSE_ID BIGINT not null,
 MARKS int default 0,
 CHECK (MARKS <= 100)
)

问题:

  1. 我是否需要为每个数据库表创建一个 pojo>
  2. 如何设置注释以实现此功能?
4

1 回答 1

2

这是简单的映射:

@Entity
@Table(name = "STUDENT")
public Class Student {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "student")
    private Set<StudentCourseMark> studentCourseMark = new HashSet<StudentCourseMark>(0);

}

@Entity
@Table(name = "COURSE")
public Class Course {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "course")
    private Set<StudentCourseMark> studentCourseMark = new HashSet<StudentCourseMark>(0);

}

@Entity
@Table(name = "STUDENT_COURSE_MARKS")
public Class StudentCourseMark {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "STUDENT_ID")
    private Student student;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "COURSE_ID")
    private Course course;

    private List<Mark> marks = new ArrayList<Mark>(0);
}

当然,您可以在您的 中使用 PrimaryKey STUDENT_ID,这里是示例: http ://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/COURSE_IDStudentCourseMark

如何获得学生成绩:

Student student = getStudentFromDB();
List<Mark> marks = student.getMarks();
于 2013-08-29T12:41:27.087 回答