我正在使用Netbeans中的derby示例数据库。我想创建一对多关系的表。
我有courses
和student
。课程应该让所有学生都参加这个课程,学生应该有他的课程。到目前为止我创建了
CREATE TABLE Course
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(50) NOT NULL,
CONSTRAINT primary_key PRIMARY KEY (id)
);
CREATE TABLE Student
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(50) NOT NULL,
surname VARCHAR(50) NOT NULL,
faculty VARCHAR(50) NOT NULL,
course_id INTEGER NOT NULL,
CONSTRAINT student_pk PRIMARY KEY (id),
CONSTRAINT student_fk FOREIGN KEY (course_id) REFERENCES course
);
但是当我使用Hibernate
进行映射时,student对象没有将course属性作为整个对象,而只将其id作为整数。
另外,如何为课程表创建多对一的关系?
感谢您的帮助!
答案 0 :(得分:1)
您的关系映射应如下所示:
@Entity
class Course{
@OneToMany(mappedBy = "course")
private Set<Student> students;
}
@Entity
class Student
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
}