Hibernate One To Many Example (XML Mapping)

By | 2017-01-20T07:34:39+00:00 November 7th, 2015|Hibernate|0 Comments

In OOPs each entity can have some relation with another entity. We need to find out which relationship can exist between the two entities. A one to many relationship can occurs, if an entity is related to multiple occurrences in another entity. In this tutorial, we are going to implement one to many relationship using hibernate.

Hibernate One to Many Relationship :

Hibernate provides us to represent the entities with relationships. To implement one to many relationship between the two components. we need to define the association relationship between the two classes. That is we need to have the dependency of child class in parent class.

A common example for one to many relationship is, Customer and Items i.e., a customer can order multiple Items.  Here the relationship between Customer to Item is one to many relationship.


Hibernate one to many Relation ExmpleAs this is a one to many relationship, a parent entity can have multiple child entities. In order to define the multiple child entities in the parent entity, hibernate API allows us to use Collection type (List,Set,Map) to define multiple child entities.

Recommended : A complete CRUD Application Using Hibernate

So that in parent entity, we need to take a reference of type Collection, it might be java.util.Set or java.util.List or java.util.Map. In parent class mapping file (customer.hbm.xml) we need to configure the same.

Let us do the example for one to many relationship. Here is the complete example.

Example for hibernate One to Many Relationship :

Create the database tables like below :

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

    `customerid_fk` INT(11) NULL DEFAULT NULL,
    `itemid` INT(11) NULL DEFAULT NULL,
    `itemname` VARCHAR(50) NULL DEFAULT NULL,
    INDEX `FK_item_customer` (`customerid_fk`),
    CONSTRAINT `FK_item_customer` FOREIGN KEY (`customerid_fk`) REFERENCES `customer` (`custid`)

Project Structure :

Hibernte one to many exampleCreate Model classes :


package com.onlinetutorialspoint.hibernate.model;

import java.util.Set;

public class Customer {

    private int customerId;
    private String customerName;
    private String city;
    private Set items;

    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;

    public Set getItems() {
        return items;

    public void setItems(Set items) {
        this.items = items;



package com.onlinetutorialspoint.hibernate.model;

public class Items {

    private int itemId;
    private String itemName;
    private int price;

    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;


Create 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"/>
        <set name="items" cascade="all">
            <key column="customerid_fk"/>
            <one-to-many class="com.onlinetutorialspoint.hibernate.model.Items"/>

Recommended : Hibernate Difference between get() and load()


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

<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.onlinetutorialspoint.hibernate.model.Items" table="item">
        <id name="itemId" column="itemid"/>
        <property name="itemName" column="itemname"/>
        <property name="price" column="price"/>

Create DAO Classes :


package com.onlinetutorialspoint.hibernate.dao;

import com.onlinetutorialspoint.hibernate.model.Customer;

public interface OneToManyDAO {

    void saveCustomer(Customer customer);


package com.onlinetutorialspoint.hibernate.dao;

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

public class OneToManyDAOImpl implements OneToManyDAO {

    public void saveCustomer(Customer customer) {
        SessionFactory factory = HibernateUtil.getInstnce();
        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();



package com.onlinetutorialspoint.hibernate.dao;

public class OneToManyDAOFactory {

    public static OneToManyDAO getInstance() {
        return new OneToManyDAOImpl();

Create HibernateUtility 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 create client class :


import com.onlinetutorialspoint.hibernate.dao.OneToManyDAO;
import com.onlinetutorialspoint.hibernate.dao.OneToManyDAOFactory;
import com.onlinetutorialspoint.hibernate.model.Customer;
import com.onlinetutorialspoint.hibernate.model.Items;
import java.util.HashSet;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        Customer customer = new Customer();

        Items i1 = new Items();

        Items i2 = new Items();

        Set items = new HashSet();


        OneToManyDAO dao = OneToManyDAOFactory.getInstance();

Output : 

Hibernate: insert into customer (custname, city, custid) values (?, ?, ?)
Hibernate: insert into item (itemname, price, itemid) values (?, ?, ?)
Hibernate: insert into item (itemname, price, itemid) values (?, ?, ?)
Hibernate: update item set customerid_fk=? where itemid=?
Hibernate: update item set customerid_fk=? where itemid=?

By running the Main.class, we can observe the above output. On the above out put first hibernate performs the insert operation in customer table and after that the corresponding child tables insertion also done.

But in Main.java we didn’t perform any save() operation on Items  class. Based on the configuration <one-to-many> tag in customer.hbm.xml file, hibernate will understand the relationship between the Customer and Items entities.


Download Example

About the Author:

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+ ,

Leave A Comment