Wednesday , June 28 2017
Home / Hibernate / Many to One Mapping in Hibernate Example

Many to One Mapping in Hibernate Example


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.

Many to One Mapping :

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.

Note : In hibernate, if relationship ends with “TO-Many” then we need a reference variable of type Collection in parent class. If the relationship ends with “To-One” then we need a reference variable of type parent class in child class.

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

Many to One Mapping Example :

To implement the Many to One Mapping in Hibernate, we need to use the <many-to-one> tag to configure the parent class.

Syntax :

many to one in hibernate exampleDataBase Schema :

    `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`)

CREATE TABLE `customer` (
    `custid` INT(11) NOT NULL,
    `custname` VARCHAR(255) NULL DEFAULT NULL,
    PRIMARY KEY (`custid`)

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) { = 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 :


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.onlinetutorialspoint.hibernate.model.Customer" table="customer">
        <id name="customerId" column="custid"/>
        <property name="customerName" column="custname"/>
        <property name="city" column="city"/>


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "">
  <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"/>

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);

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();;


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();

        Item i1 = new Item();

        Item i2 = new Item();

        ManyToOneDAO dao = ManyToOneDAOFactory.getInstance();

Output :
Hibernate: select customer_.custid, customer_.custname as custname0_, 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_, 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 :

Many to one in hibernate DB

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

Leave a Reply

Your email address will not be published. Required fields are marked *