Hibernate Many-to-One Mapping

Many-to-One Hibernate Mapping with Example

A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class object to parent class object. It is an N to 1 relationship.

For example, there are many customers of a single vendor; it is just the reverse of one-to-many association mapping. Here, we need to take a collection property like Set, Map, Bag, and List in the Customer.java class.

Now, we are going to create an example, in which there are two persistent classes, i.e., Customers and Vendor. Here, we are taking a unidirectional mapping, so we need to define @ManyToOne and @JoinColumn annotations in the Customer class.

Following are the steps to create the example:

  1. Create all persistent classes

In this step, we are going to develop persistent classes, i.e., Vendor.java and Customer.java.

Vendor.java

import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.Table;
 @Entity 
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.Table;
 @Entity 
 @Table(name="vend")
 public class Vendor {
  @Id
  @Column(name="vend_id")
  private int v_id; 
  @Column(name="v_name")
  private String name;
  public int getV_id() {
  return v_id;
  } 
  public void setV_id(int v_id) {
  this.v_id = v_id;
  }
  public String getName() {
  return name; 
  }
  public void setName(String name) {
  this.name = name;
  }
  } 

Customer.java

import javax.persistence.CascadeType;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
 import javax.persistence.ManyToOne;
 import javax.persistence.Table; 
 @Entity
 @Table(name="custo")
 public class Customer {
  @Id
  @Column(name="cust_id")
  private int c_id;
  @Column(name="cust_name")
  private String name;
  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="v_id",referencedColumnName="vend_id")
  private Vendor v;
  public int getC_id() {
  return c_id;
  }
  public void setC_id(int c_id) {
  this.c_id = c_id;
  }
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  public Vendor getV() {
  return v;
  }
  public void setV(Vendor v) {
  this.v = v;
  }
  } 
  • Create the configuration file

In this step, we are going to create the configuration class (hibernate.cfg.xml) which contains the information of persistent class and the database.

hibernate.cfg.xml

 
  
  
  
 update 
 org.hibernate.dialect.MySQL5Dialect
 com.mysql.jdbc.Driver
 jdbc:mysql://localhost:3306/test
 root 
 root 
  
  
  
   
  • Create the main class that stores the object of  the persistent class

In this step, we are going to create a class which consists of main() method, and stores the objects of persistent classes.

App.java

import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 public class App 
 {
  public static void main( String[] args )
  {
  Configuration cfg= new Configuration();
  cfg.configure("hibernate.cfg.xml");
  SessionFactory factory= cfg.buildSessionFactory();
  Session session= factory.openSession();
  Vendor ven= new Vendor();
  ven.setV_id(101);
  ven.setName("jahanvi");
  Customer c= new Customer();
  c.setC_id(201);
  c.setName("Nihal");
  c.setV(ven);
  Customer c2 =new Customer();
  c2.setC_id(202);
  c2.setName("Rajak");
  c2.setV(ven);
  Transaction t= session.beginTransaction();
  session.save(c);
  session.save(c2);
  t.commit();
  session.close();
  System.out.println("saved successfuly!!");
  factory.close();
  }
 } 
  • Output
Many-to-One Hibernate Mapping
  • Table

Custo table

Custo table Many-to-One Hibernate Mapping

Vend table

Vend table Many-to-One Hibernate Mapping

Related Topics

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

3 minutes read.

Hibernate Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

2 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Hibernate Merge

Hibernate Merge Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge()...

2 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.

Hibernate Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

3 minutes read.

Hibernate GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Hibernate Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

2 minutes read.

Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes the...

2 minutes read.

Hibernate Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the...

2 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Architecture of Hibernate

Next → Hibernate is an ORM framework with a layered architecture. It consists of many objects, such as a persistent object, sessionfactory object, transaction object, session, etc.  There are mainly three layers in Hibernate...

2 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.