I am playing with derby sample database in Netbeans. I want to create tables with one to many relation.
I have courses
and student
. Course should have all students that take this course in its table and student should have course that he is taking in its table. So far i created
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
);
However when i map this using Hibernate
, the student object does not have course property as whole object , but only its id as integer.
Also how could I create many to one relation for course table?
Thanks for help!
Your relationship mappings should look like this:
@Entity
class Course{
@OneToMany(mappedBy = "course")
private Set<Student> students;
}
@Entity
class Student
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
}