Updated April 1, 2023
Introduction to Hibernate Many to One
Hibernate Many to One mapping means that many rows in a table are mapped to one row in another table.
This is the association diagram to understand one to many relationships:
Modelling a database involves defining several one to many relationships or many to one relationships. Also the same, when you are modelling the entities. JPA and Hibernate are chosen to do the task easily. Annotating an attribute taken that represents the associations one to many and many to one is what one needs. Many to one is an Unidirectional annotation based configuration.
Syntax:
public class Cart {
//...
@OneToMany(mappedBy="cart")
private Set<Items> items;
//...
}
Adding reference to items in cart using the many to one, can make it a bidirectional relationship. Which means, we can access the items both ways, that is, carts from items and items from cart.
How Hibernate Many to One Annotation Works?
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 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 address and student table.
Code:
package com.tutorial.student_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 = "STUDENT NAME")
public class Student {
private long Id;
private String Name_Of_Student;
private Address Address_Of_Student;
public Student() {
}
public Student(String Name_Of_Student, Address Address_Of_Student) {
this.studentName = Name_Of_Student;
this.Address_Of_Student = Address_Of_Student;
}
@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, length = 150)
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;
}
@ManyToOne(cascade = CascadeType.ALL) //cascade equals save
public Address getAddress_Of_Student() {
return this.Address_Of_Students;
}
public void setAddress_Of_Student(Address Address_Of_Student) {
this.Address_Of_Student = Address_Of_Student;
}
}
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-one relationships using annotations of hibernate. Considering the relationship between address and students as entities.
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.
package com.tutorial.student_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 = "ADDRESS_INFORMATION")
public class Address_Of_Student {
private String zipcode_number;
private String street_name;
private String state_name;
private String city_name;
private long addressId;
public Address_Of_Student() {
}
public Address_Of_Student(String zipcode_number,String state_name,String city_name,String street_name) {
this.street = street_name;
this.city = city_name;
this.state = state_name;
this.zipcode = zipcode_number;
}
@Id
@GeneratedValue
@Column(name = "ID_OF_ADDRESS")
public long getId() {
return this.Id;
}
public void setId(long Id) {
this.Id = Id;
}
@Column(name = "STREE_OF_ADDRESS_T", nullable = false)
public String getStreet_name() {
return this.street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
@Column(name = "CITY_OF_ADDRESS", nullable = false)
public String getCity_name() {
return this.city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
@Column(name = "STATE_OF_ADDRESS", nullable = false)
public String getState_name() {
return this.state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
@Column(name = "ZIPCODE_OF_ADDRESS", nullable = false)
public String getZipcode_number() {
return this.zipcode_number;
}
public void setZipcode_number(String zipcode_number) {
this.zipcode_number = zipcode_number;
} }
In main class:
package com.tutorial.student_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();
Address_Of_Student address_information = new Address_Of_Student("60097", "TN", "Chennai", "OMR Road");
Student_information first_Student = new Student_information("Eswar", address_information);
Student_information second_Student = new Student_information("Joe", address_information);
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 :
Table of students has two records.
Table of Address has one record.
The many-to-one mapping association is seen as the students record the same address.
Conclusion
When you model your databases, you will be most likely to find and define several associations. One of such is the Many-To-One relationship. And its easy to do that with Hibernate and JPA. Take an attribute that represents the association and annotate it with many-to-one.
Recommended Articles
This is a guide to Hibernate Many to One. Here we discuss How Hibernate Many to One Annotation Works and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –