Many to One Mapping in Hibernate | many to one relationship

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to implement many to one mapping in hibernate.
In our relational database systems, a many to one relationship occur when multiple child records in one table can refer to one single record in parent table. This example explains you how to map the many to one relationship with hibernate.
To map the entities with many to one relationship in hibernate, we need to define the association between those entities. That is we need to define the parent class dependency (parent class reference variable) in child class.
The operations (Save, Update, Delete) should be performed from the child class only. The corresponding parent class would be effected automatically by using the many to one mapping configuration in hibernate mapping file (hbm.xml).
This is completely opposite functionality when compare with the one to many mapping in hibernate.
In our example, we are going to use the Customer and Item entities for this many to one mapping. Multiple Items can order by a single Customers, So that Item to Customer is many to one relationship.
If we apply the Many to One mapping for the Item to Customer then, in Item class we need a reference variable of Customer type.
Recommended : one to many mapping using xml configuration 
To implement the Many to One Mapping in Hibernate, we need to use the <many-to-one> tag to configure the parent class.
Syntax :
DataBase Schema :

CREATE TABLE `item` (
    `itemid` INT(11) NOT NULL,
    `itemname` VARCHAR(255) NULL DEFAULT NULL,
    `price` INT(11) NULL DEFAULT NULL,
    `customer` INT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`itemid`),
    INDEX `FK317B1357A84770` (`customer`),
    CONSTRAINT `FK317B1357A84770` FOREIGN KEY (`customer`) REFERENCES `customer` (`custid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

CREATE TABLE `customer` (
    `custid` INT(11) NOT NULL,
    `custname` VARCHAR(255) NULL DEFAULT NULL,
    `city` VARCHAR(255) NULL DEFAULT NULL,
    PRIMARY KEY (`custid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;


Creating Model Classes :
package com.onlinetutorialspoint.hibernate.model;

public class Customer {

    private int customerId;
    private String customerName;
    private String city;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}


package com.onlinetutorialspoint.hibernate.model;

public class Item {

    private int itemId;
    private String itemName;
    private int price;
    private Customer customer;

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

}


Creating Hibernate Mapping Files :
customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.onlinetutorialspoint.hibernate.model.Customer"
    table="customer">
    <id name="customerId" column="custid" />
    <property name="customerName" column="custname" />
    <property name="city" column="city" />
  </class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.onlinetutorialspoint.hibernate.model.Item"
    table="item">
    <id column="itemid" name="itemId" />
    <property column="itemname" name="itemName" />
    <property column="price" name="price" />
    <many-to-one class="com.onlinetutorialspoint.hibernate.model.Customer"
      name="customer" cascade="all" />
  </class>
</hibernate-mapping>
Recommended : Spring with Hibernate Example
Creating DAO Classes :
package com.onlinetutorialspoint.hibernate.dao;

import com.onlinetutorialspoint.hibernate.model.Item;

public interface ManyToOneDAO {

    void saveItem(Item item);
}


ManyToOneDAOImpl.java
package com.onlinetutorialspoint.hibernate.dao;

import com.onlinetutorialspoint.hibernate.model.Item;
import com.onlinetutorialspoint.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class ManyToOneDAOImpl implements ManyToOneDAO {

    public void saveItem(Item item) {
        
        SessionFactory factory = HibernateUtil.getInstnce();
        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();
        session.save(item);
        tx.commit();
        session.close();
    }

}


package com.onlinetutorialspoint.hibernate.dao;

public class ManyToOneDAOFactory {

    public static ManyToOneDAO getInstance() {
        return new ManyToOneDAOImpl();
    }
}


Creating Hibernate Utility Class :
package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private HibernateUtil() {

    }
    private static SessionFactory sessionFactory;

    public static synchronized SessionFactory getInstnce() {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        }
        return sessionFactory;

    }
}

To Run The Application Creating Main Class :
import com.onlinetutorialspoint.hibernate.dao.ManyToOneDAO;
import com.onlinetutorialspoint.hibernate.dao.ManyToOneDAOFactory;
import com.onlinetutorialspoint.hibernate.model.Customer;
import com.onlinetutorialspoint.hibernate.model.Item;

public class Main {

    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.setCustomerId(1001);
        customer.setCustomerName("Rahul");
        customer.setCity("Mumbai");

        Item i1 = new Item();
        i1.setItemId(9001);
        i1.setItemName("Samsung");
        i1.setPrice(9000);
        i1.setCustomer(customer);

        Item i2 = new Item();
        i2.setItemId(9002);
        i2.setItemName("LG");
        i2.setPrice(6000);
        i2.setCustomer(customer);

        ManyToOneDAO dao = ManyToOneDAOFactory.getInstance();
        dao.saveItem(i1);
        dao.saveItem(i2);
    }
}

Hibernate: select customer_.custid, customer_.custname as custname0_, customer_.city as city0_ from customer customer_ where customer_.custid=? 
Hibernate: insert into customer (custname, city, custid) values (?, ?, ?) Hibernate: insert into item (itemname, price, customer, itemid) values (?, ?, ?, ?) 
Hibernate: select customer_.custid, customer_.custname as custname0_, customer_.city as city0_ from customer customer_ where customer_.custid=? 
Hibernate: insert into item (itemname, price, customer, itemid) values (?, ?, ?, ?)
On the above output, Hibernate first fire a select query in database, instead of directly insert the data into customer table.
In many to one mapping, when we save the child object, hibernate first checks whether its parent object is exist in database or not. If parent object is exist then hibernate inserts only child records. If doesn’t exist hibernate first inserts the parent record and then insert the child records.
Database Output

Happy Learning 🙂


Many-to-One-Hibernate Complete Example

File size: 20 KB
Downloads: 829


Hibernate Right Join Example
Hibernate Left Join Example
Custom Generator Class in Hibernate
Hibernate orderby criteria Example
Hibernate Named Query with Example
Hibernate Pagination Example
Hibernate groupby criteria HQL query Example
Hibernate One To Many Using Annotations
Table per Sub Class in Hibernate Inheritance
Hibernate One To Many Example (XML Mapping)
Hibernate Many to Many Mapping Example (XML)
Hibernate Composite Key Mapping Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One to One Mapping using primary key (XML)
Hibernate Inheritance Mapping Strategies

Hibernate Right Join Example
Hibernate Left Join Example
Custom Generator Class in Hibernate
Hibernate orderby criteria Example
Hibernate Named Query with Example
Hibernate Pagination Example
Hibernate groupby criteria HQL query Example
Hibernate One To Many Using Annotations
Table per Sub Class in Hibernate Inheritance
Hibernate One To Many Example (XML Mapping)
Hibernate Many to Many Mapping Example (XML)
Hibernate Composite Key Mapping Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One to One Mapping using primary key (XML)
Hibernate Inheritance Mapping Strategies






Arun Singh
August 11, 2018 at 6:28 am - Reply 

“If parent object is exist then hibernate inserts only child records. If doesn’t exist hibernate first inserts the parent record and then insert the child records.”
Hi sir,
Your statement is incorrect.
If “Cascade=All” and parent object already exists in DB then Hibernate will throw “org.hibernate.exception.ConstraintViolationException”









Arun Singh
August 11, 2018 at 9:41 am - Reply 

i apologise, i was wrong. please don’t consider my comment












Arun Singh
August 11, 2018 at 6:28 am - Reply 

“If parent object is exist then hibernate inserts only child records. If doesn’t exist hibernate first inserts the parent record and then insert the child records.”
Hi sir,
Your statement is incorrect.
If “Cascade=All” and parent object already exists in DB then Hibernate will throw “org.hibernate.exception.ConstraintViolationException”









Arun Singh
August 11, 2018 at 9:41 am - Reply 

i apologise, i was wrong. please don’t consider my comment






“If parent object is exist then hibernate inserts only child records. If doesn’t exist hibernate first inserts the parent record and then insert the child records.”
Hi sir,
Your statement is incorrect.
If “Cascade=All” and parent object already exists in DB then Hibernate will throw “org.hibernate.exception.ConstraintViolationException”





Arun Singh
August 11, 2018 at 9:41 am - Reply 

i apologise, i was wrong. please don’t consider my comment




i apologise, i was wrong. please don’t consider my comment
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache