Hibernate Mapping One to Many using Annotation Example

We already created Simple Hibernate Application, in this tutorial we'll see Hibernate One to Many Mapping with Example. Click Here for Hibernate Example Project With Annotation

For this Hibernate One to Many Mapping application we'll follow following steps:


Step 1: Create a Java Project using Eclipse IDE

Step 2: Download & Add Hibernate jar Files

Step 3: Download & Add MySQL connector jar File

Click Here for all the above steps

Step 4: Create a Hibernate Configuration File

hibernate.cfg.xml'
<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/my_db</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Drop the existing table and create new one -->
        <property name="hbm2ddl.auto">create</property>
  
        <!-- Mention here all the model classes -->
        <mapping class="com.blogspot.sonevalley.model.CustomerEntity"/>
        <mapping class="com.blogspot.sonevalley.model.OrderEntity"/>

    </session-factory>

</hibernate-configuration>

Step 5: Add the below Files to Project

HibernateUtil.java is used to return SessionFactory
HibernateUtil.java
package com.blogspot.sonevalley.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 
 private static SessionFactory sessionFactory;
 private static SessionFactory buildSessionFactory() {
  try {
   // Creating the SessionFactory from hibernate.cfg.xml
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   return sessionFactory;
   
  } catch(Throwable ex) {
   ex.printStackTrace();
   throw new ExceptionInInitializerError(ex);
  }
 }
 
 public static SessionFactory getSessionFactory() {
  if(sessionFactory == null) {
   sessionFactory = buildSessionFactory();
  }
  return sessionFactory;
 }

}

We'll create two Hibernate Persistence Classes (Model Class) CustomerEntity.java and OrderEntity.java

CustomerEntity class is used to create the customer table
CustomerEntity.java
package com.blogspot.sonevalley.model;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class CustomerEntity {
 
 @Id
 @GeneratedValue
 private long customerId;
 private String customerName;
 
 public CustomerEntity(String customerName) {
  super();
  this.customerName = customerName;
 }
 public long getCustomerId() {
  return customerId;
 }
 public void setCustomerId(long customerId) {
  this.customerId = customerId;
 }
 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }
 
 @OneToMany(targetEntity = OrderEntity.class, mappedBy = "customer", fetch=FetchType.EAGER)
 private Set<OrderEntity> orders = new HashSet<>();
 public Set<OrderEntity> getOrders() {
  return orders;
 }
 public void setOrders(Set<OrderEntity> orders) {
  this.orders = orders;
 }
}

OrderEntity class is used to create the orders table
OrderEntity.java
package com.blogspot.sonevalley.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "orders")
public class OrderEntity {

 @Id
 @GeneratedValue
 private long orderId;
 private String orderName;
 
 public OrderEntity(String orderName) {
  super();
  this.orderName = orderName;
 }
 
 public long getOrderId() {
  return orderId;
 }
 public void setOrderId(long orderId) {
  this.orderId = orderId;
 }
 public String getOrderName() {
  return orderName;
 }
 public void setOrderName(String orderName) {
  this.orderName = orderName;
 }
 
 @ManyToOne
 @JoinColumn(name="customerId")
 private CustomerEntity customer;
 public CustomerEntity getCustomer() {
  return customer;
 }
 public void setCustomer(CustomerEntity customer) {
  this.customer = customer;
 }
}

Create Main Application Class
Main.java
package com.blogspot.sonevalley.main;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.blogspot.sonevalley.model.CustomerEntity;
import com.blogspot.sonevalley.model.OrderEntity;
import com.blogspot.sonevalley.util.HibernateUtil;

public class Main {
 
 public static void main(String[] args) {
  
  Transaction transaction = null;
  SessionFactory sessionFactory = null;
  CustomerEntity customer1 = new CustomerEntity("Sushil Kumar");
  CustomerEntity customer2 = new CustomerEntity("Vijay Pandey");
  OrderEntity order1 = new OrderEntity("Pizza");
  OrderEntity order2 = new OrderEntity("Coke");
  
  try {
   sessionFactory = HibernateUtil.getSessionFactory();
   Session session = sessionFactory.getCurrentSession();
   transaction = session.beginTransaction();
   
   session.save(customer1);
   session.save(customer2);
   
   order1.setCustomer(customer1);
   order2.setCustomer(customer1);
   session.save(order1);
   session.save(order2);
   
   transaction.commit();
   System.out.println("Record(s) Saved!");
   
  } catch(HibernateException e) {
   transaction.rollback();
   e.printStackTrace();
  } finally {
   sessionFactory.close();
  }
 }
}


Directory Structure (Package Explorer)

Directory Structure in Package Explorer

Step 6: Run the Project

Right Click on the Project
Click on Run as -> Java Application
Console output after running the project successfully
Console Output of Hibernate One-to-Many Mapping
Console Output


Customer and Orders table after running the project successfully
customer table
orders table


Click on the below button to download this project

Download Project



SHARE
    Blogger Comment
    Facebook Comment

1 comments:

  1. Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
    Java Training in Electronic City

    ReplyDelete