In @OneToMany making One's side owner

72 Views Asked by At

Let's say there is an Employee's which has a collection of Course.

class Employee {
@OneToMany
private Set<Course> courses.
}

I want something like below

first_name | last_name | course_ids
Jill       |  Smith.   | 1,2,3
Eve        |  Jackson. | 1,4,5

I am not so advanced in hibernate, can someone please help.

1

There are 1 best solutions below

0
On

The method that I am about to show to you is the One to many unidirectional method. In your database you should create a table for courses and it must contain employee_id as a foreign key and an id of the course as a primary key. Then, create the Course class as below.(let's assume that the name of the course table in the database is "course":

@Entity
@Table(name = "course")
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ='id')
    private int id;
    
    //You can add another fields based on your course table
   //add a constructor with no arguments, getters and setters
}

Notice that the employee_id is not in the course class.Then create the employee class:

@Entity
@Table(name ="employee")
public class Employee {
    //ID and other fields
    @OneToMany
    @JoinColumn(name="course_id")
    private List<Course> courses;
    
    //Constructor,getters and setters,...

}

You must define getters and setters in every Entity you create because Hibernate uses them to set the fields in the Entity with the value retrieved from the database