Updated April 1, 2023
Introduction to Hibernate Many to Many
Hibernate Many To Many mapping means that many rows in a table are mapped to many rows in the other table. It can also be said, where the mapping is made between the entities in such a way that one can have many associations with other instances of another entity.
This is the association diagram to understand many to many relationships:
Modeling a database involves defining several ones to many, many to one or many to many relationships. Also the same, when you are modeling the entities. JPA and Hibernate are chosen to do the task easily. Annotating an attribute taken that represents the associations one too many and many to one are what one needs. Many to Many is a Bidirectional annotation-based configuration.
Syntax
public class Cart {
//...
@ManyToMany(mappedBy="cart")
private Set<Items> items;
//...
}
Adding a reference to items in the cart using the many-to-many, is a bidirectional relationship. This means, we can access the items both ways, that is, carts from items and items from the cart.
How does Hibernate Many-To-Many Annotation work?
Hibernate tells us which variable we use to represent the parent class in the child class by the mappedBy property. The below are the libraries used to develop a sample application of Hibernate which implements one-to-many association:
H2 database
Hibernate 5
JDK 1.8 and later
Maven 3 and later
The below will be showing the relationship between the entities.
Firstly, create a java class with the hibernate annotations to create the courses of student and the student details table.
Code:
package com.tutorial.student_course_information;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerateionType;
import javax.persistence.Id;
import javax.persistence.JonColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "STUDENT_NAME")
public class Student {
private long Id;
private String Name_Of_Student;
private Set<course_details> course_details = new HashSet<course_details>();
public Student() {
}
public Student(String Name_Of_Student, Set<course_details> course_details)
this.Name_Of_Student = Name_Of_Student;
this.course_details = course_details;
}
@Id
@GeneratedValue
@Column(name = "ID")
public long getId() {
return this.Id;
}
public void setId(long Id) {
this.Id = Id;
}
@Column(name = "NAME_OF_STUDENT", nullable = false)
public String getName_Of_Student() {
return this.Name_Of_Student;
}
public void setName_Of_Student(String Name_Of_Student) {
this.Name_Of_Student = Name_Of_Student;
}
@ManyToMany(cascade = CascadeType.ALL) //cascade equals save
@JoinTable(name = "COURSE_OF_STUDENT", joinColumns = { @JoinColumn(namw = "ID") })
public Set<course_details> getcourse_details() {
return this.course_details;
}
public void setcourse_details(Set<course_details> course_details) {
this.course_details = course_details;
}
}
And thus, the database setup is about ready. Now, let’s create an example: Now, in this example, we will see how to map many-to-many relationships using annotations of hibernate. Considering the relationship between courses and student details as entities. Where each instance can be accessed with any of which it is associated with the other entity.
cascade is used to cascade the operations with associated entities. For example, if you have an object of a student, the address associated with it will be saved automatically.
The annotation: JoinTable is used in creating the course details tab and
The annotation: @JoinColumn is used to link the two tables.
Code:
package com.tutorial.student_course_information;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerateionType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "COURSE_DETAILS")
public class course_details {
private long id_of_the_course;
private String course_details_name;
public course_details() {
}
public course_details(String course_details_name) {
this.course_details_name = course_details_name;
}
@Id
@GeneratedValue
@Column(name = "ID")
public long getId() {
return this.Id;
}
public void setId(long Id) {
this.Id = Id;
}
@Column(name = "COURSE_DETAILS", nullable = false)
public String getcourse_details_name() {
return this.course_details_name;
}
}
In the main class:
package com.tutorial.student_course_information;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.tutorial.util.HibernateUtil;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Set<course_name> course_name = newHashSet<course_name>()
course_name.add new course_name(("Computers"));
course_name.add course_name(("Mathematics"));
Name_Of_Student first_Student = new Name_Of_Student("Eswar",course_name);
Name_Of_Student second_Student = new Name_Of_Student("Joe", course_name);
session.save(first_Student);
session.save(second_Student);
transaction.commit();
} catch (HibernateException e) {
if (transaction! = null)
transaction.rollback():
e.printStackTrace();
} finally {
session.close();
}
}
HibernateUtil.shutdown():
}
Output:
The table of name_of_student has two records.
The table of course_name has two records.
There are four records linked in the student_course_information table:
The many-to-many mapping is seen as each student is enrolled in a similar course.
Conclusion
When you model your databases, you will be most likely to find and define several associations. One of such is the Many-To-Many relationship. And it is easy to do that with Hibernate and JPA. Take an attribute that represents the association and annotate it with many-to-many. This illustrates that one object relates to many other objects in another entity.
Recommended Articles
This is a guide to Hibernate Many to Many. Here we discuss an introduction and how the annotation works with examples for better understanding. You can also go through our other related articles to learn more –