hibernate one to many | one to many mapping in hibernate

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 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 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.
 
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.
Create the database tables like below :

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 :
Create Model classes :
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
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
<?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
<?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
package com.onlinetutorialspoint.hibernate.dao;

import com.onlinetutorialspoint.hibernate.model.Customer;

public interface OneToManyDAO {

    void saveCustomer(Customer customer);
}
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
package com.onlinetutorialspoint.hibernate.dao;

public class OneToManyDAOFactory {

    public static OneToManyDAO getInstance() {
        return new OneToManyDAOImpl();
    }
}
Create HibernateUtility Class :
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
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 :
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 🙂


Hibernate One To Many Relation Complete Example

File size: 20 KB
Downloads: 951


Many to One Mapping in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate Many to Many Mapping Example (XML)
Hibernate One to One Mapping using primary key (XML)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate Composite Key Mapping Example
Hibernate One To Many Using Annotations
Basic Hibernate Example with XML Configuration
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Inheritance Mapping Strategies
Hibernate Named Query with Example
Custom Generator Class in Hibernate
Hibernate Interceptor Example

Many to One Mapping in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate Many to Many Mapping Example (XML)
Hibernate One to One Mapping using primary key (XML)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate Composite Key Mapping Example
Hibernate One To Many Using Annotations
Basic Hibernate Example with XML Configuration
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Inheritance Mapping Strategies
Hibernate Named Query with Example
Custom Generator Class in Hibernate
Hibernate Interceptor Example






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.










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.




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


Δ
 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