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.
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 :
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.
Happy Learning 🙂