我正在使用 hibernate 开发一个学生信息系统,学生可以在其中拥有多个类(class)(和分数)。我希望我的 POJO 是这样的:
学生:student attributes + Set<Course>
类(class):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)
)
问题:
- 我需要为每个数据库表创建一个 pojo>
- 如何设置注释来实现此功能?
最佳答案
这是简单的映射:
@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);
}
当然,您可以在 StudentCourseMark
中的 STUDENT_ID
、COURSE_ID
上使用 PrimaryKey,示例如下:
http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/
如何获得学生分数:
Student student = getStudentFromDB();
List<Mark> marks = student.getMarks();
关于java - Hibernate - 学生评分系统。需要注释方面的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510987/