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 Exmple

As 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 :

SQL Tables

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

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

Project Structure :

Hibernte one to many example

Create Model classes :

Customer.java

Customer.java
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;
    }

}

Items.java

Items.java
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 :

customer.hbm.xml

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

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

items.hbm.xml

items.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.Items" table="item">
        <id name="itemId" column="itemid"/>
        <property name="itemName" column="itemname"/>
        <property name="price" column="price"/>
    </class>
</hibernate-mapping>

Create DAO Classes :

OneToManyDAO.java

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

import com.onlinetutorialspoint.hibernate.model.Customer;

public interface OneToManyDAO {

    void saveCustomer(Customer customer);
}

OneToManyDAOImpl.java

OneToManyDAOImpl.java
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();
        session.save(customer);
        tx.commit();
        session.close();
    }

}

OneToManyDAOFactory.java

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

public class OneToManyDAOFactory {

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

Create HibernateUtility Class :

HibernateUtil.java

HibernateUtil.java
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 :

Main.java

Main.java
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();
        customer.setCustomerId(1001);
        customer.setCustomerName("Dinesh");
        customer.setCity("Banglore");

        Items i1 = new Items();
        i1.setItemId(9001);
        i1.setItemName("Samsung");
        i1.setPrice(9000);

        Items i2 = new Items();
        i2.setItemId(9002);
        i2.setItemName("LG");
        i2.setPrice(6000);

        Set items = new HashSet();
        items.add(i1);
        items.add(i2);

        customer.setItems(items);

        OneToManyDAO dao = OneToManyDAOFactory.getInstance();
        dao.saveCustomer(customer);
    }
}

Output :

Terminal
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.

Happy Learning 🙂

Download Example

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

One Comment

  1. Sravya March 28, 2021 at 7:02 am - Reply

    Wow..finally found a good site for learning hibernate with best examples.
    Thank you so much.

Leave A Comment