Relationships in Hibernate with SpringBoot(@OneToMany and @ManyToOne)

Relationship Mapping in Hibernate2

In this lesson, I would explain to you how relationships works in hibernate. Then I would give you a practical as well.

We would be using two classes:

  • Student: List of students with fields – Id, firstname and lastname
  • Department: List of department with fields – Id, name and description

The Student class would correspond to the Student table while the Department class would correspond to Department table.

Now the relationship is such that:

many student would belong to one department – that is ManyToOne (many students, one department)

one department can contain many students – that is OneToMany(on department, many students)


How then do we implement this in Spring?

So let’s begin with the Student class. This is shown below. Notice that we have included an additional member variable: department.

public class Student {
	private Integer Id;
	private String firstname;
	private String lastname;
	private Department department;
	//getters and setters


In the Student class, we have add the @ManyToOne annotation to the department variable. So, this simply tells hibernate that a student belongs to a department. Also, that many student can have one department.

Now let’s look at the Department class. This is shown below:

public class Department {
	private Integer Id;
	private String name;
	private String description;
	@OneToMany(mappedBy = "department")
	private List<Student> students;
	//getters and setter


Also note that in the Department class, we have added a private variable, students. Also notice that this variable is a List<Student> type. This means that we can ask the department to give us a list of students in it!. Isn’t this amazing!

The H2 Console window is shown below;

H2 Console Window for Relationships


Extra Table

Now, if you just add the @OneToMany and @ManyToOne annotations, two things would happen:

  • the Student table would be created and additional field would be added called Department_Id
  • Department table would be created together with another table( third table) called Department_Students. This is a way the Departments class tries to handle the mapping.

Somehow, we need a way  to tell the Department class that the mapping is handled by the Student class. And therefore it would not be necessary to have a third table.

To do that, we used the mappedBy attribute of the @OneToMany annotation in the Deparment class. The value is set to the field in the Student table that has the @ManyToOne annotation. In our case, this field is the department field.


I recommend you watch the video as well.



Leave a Reply

Your email address will not be published. Required fields are marked *