How to works Hibernate Many to Many?

How to works Hibernate Many to Many?
Techiio-author
Written by Sagar RabidasFebruary 15, 2022
7 min read
Hibernate
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Let's start the discussion with Hibernate Many to Many

Hibernate Many to Many:-

Hibernate has many to many mapping manners that many rows in a table are mapped to many rows inside the different desk. It can also be said, that the mapping is made between the entities in such a manner that one will have many associations with other times of some other entity.

This is the association diagram to understand many to many relationships:

Modelling a database involves defining numerous ones to many, many to 1, or many to many relationships. Additionally, the same, while you are modelling the entities. JPA and hibernate are chosen to do the project easily. Annotating a characteristic is taken that represents the institutions one too many and lots of 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 mapped by property. 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

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: Join Table 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():
}

Hibernate
HibernateManytoMany
Java
2 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance