Many to Many Relationships using Hibernate, Spring Boot (Git code link available)
I was recently asked a question related to this topic in one of the interviews. This article will explain the same concept of many to many relationships.
If you are not interested to read the article, and would want to jump to the code, then here is the git link for the same —
https://github.com/Viveksingh1313/manytomany-spring-boot
Check the readMe file for setup. Tech used : Spring Boot, Postgres12, Hibernate, Java.
We will take an example to start with. Let’s assume this as our business condition :
A student can have multiple courses.
A course can have multiple students.
Tables :
Students — sid(pkey), name, description, dateOfBirth
Courses — cid(pkey),name, description, lastUpdatedAt
Example with dataset (This is the kind of data we need to store on database)
A Student named “Vivek” with 2 courses :
1, “Vivek”, “Is my name”, 25–05–1995
1,“Maths”, “Maths is easy”, 09–19–2020
2,“Chemistry”, “Chemistry is difficult”, 09–19–2020
A Course named “Maths” with 2 students :
3, “Maths”, “Maths is tricky”, 09–19–2019 2, “John”, “John is my name”, 09–19–2020 3, “Mayer”, “is my name”, 09–19–2020
How do we maintain this relationship of many to many ?
It’s not possible using just the two tables ‘Students’ and ‘Courses’ — Because of the primary key constraint and no array-like data structure found in relational database schema.
So the best solution here is to use the 3rd table — which will maintain a relation between table ‘Students’ and ‘Courses’ . In this table we will have unique primary keys stored for both the tables which are sid, and cid.
Let the 3rd table name be ‘students_courses’ with two columns sid, and cid.
So this ‘students_courses’ table would have these kinds of values to manage the relation between the two tables :
This is pretty much about the theoretical example. Now I will explain the same concept using Hibernate, Postgres, and SpringBoot.
Using the above tech stack, we just need to maintain two tables named ‘Students’ and ‘Courses’. No need to maintain a third table in our code, this will be handled by Hibernate itself.
This is the piece of code that is needed in our Entity class :
Students Entity :
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "students_courses",
joinColumns = { @JoinColumn(name = "sid") },
inverseJoinColumns = { @JoinColumn(name = "cid") })
private Set<Courses> courses = new HashSet<>();
Courses Entity :
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "courses")
private Set<Students> students = new HashSet<>();
This is all we need to do to maintain the many to many relationships .
Let’s go through the explanation of the above code blocks for the entities:
As we need to maintain many to many relationships, we are using an annotation of @ManyToMany. @JoinTable could have been used in any of the above entities(screenshot), so do not be confused by that. @JoinTable takes a table name which is the 3rd table name here, joinColumns takes the column name to store sid(Students) in the 3rd table. inverseJoinColumns takes the column name to store cid(Courses) in the 3rd table.
Inside @ManyToMany annotation , fetch is basically how you get/fetch data from the database. When fetching, we can define whether we want to fetch the details from joined tables as well. Here LAZY just means that fetch the specific table details and leave the joined table details.
Entity relationships often depend on the existence of another entity, for example the Person–Address relationship. Without the Person, the Address entity doesn’t have any meaning of its own. When we delete the Person entity, our Address entity should also get deleted.
Cascading is the way to achieve this. When we perform some action on the target entity, the same action will be applied to the associated entity.
We will consider our example of Students-Courses relationship to describe the PERSIST and MERGE . Persist means to store Course data whenever the Student data is saved to the db, and vice versa.
MERGE means to store a new set/list of courses for a student, or to store a new set/list of students for a specific course.
Please reach out to me at vivek.sinless@gmail.com for more queries .