Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating relations in derby sample database

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!

like image 475
Darlyn Avatar asked Mar 26 '26 17:03

Darlyn


1 Answers

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;

}
like image 129
Maciej Kowalski Avatar answered Mar 28 '26 06:03

Maciej Kowalski