CRUD in Hibernate One to Many Association Annotation Example

We already created Hibernate Mapping One to Many Application for adding record to Database, in this tutorial we'll see CRUD operation in Hibernate One to Many Mapping using Association Table with Example.
Database Relations


For this Hibernate One to Many Mapping application we'll follow below 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/sonevalley</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">10</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 and customer_orders association table
CustomerEntity.java
package com.blogspot.sonevalley.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class CustomerEntity {

 @Id
 @GeneratedValue
 private long customerId;
 private String customerName;
 private String customerPhone;

 public CustomerEntity() {
  super();
 }
 public CustomerEntity(String customerName, String customerPhone) {
  super();
  this.customerName = customerName;
  this.customerPhone = customerPhone;
 }

 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;
 }
 public String getCustomerPhone() {
  return customerPhone;
 }
 public void setCustomerPhone(String customerPhone) {
  this.customerPhone = customerPhone;
 }
 
 @OneToMany(cascade = { CascadeType.ALL })
 @JoinTable(joinColumns = @JoinColumn(name = "customerId"), inverseJoinColumns = @JoinColumn(name = "orderId"))
 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.Table;

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

 @Id
 @GeneratedValue
 private long orderId;
 private String orderName;
 
 
 public OrderEntity() {
  super();
 }

 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;
 }
}


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

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

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 {
 
 private static SessionFactory sessionFactory;
 public static void main(String[] args) {
  
  try{
   sessionFactory = HibernateUtil.getSessionFactory();
  } catch(Exception e) {
   e.printStackTrace();
  }
  Main mainApp = new Main();
  
  Set<OrderEntity> orders = new HashSet<>();
  orders.add(new OrderEntity("Pizza"));
  orders.add(new OrderEntity("Coke"));
  orders.add(new OrderEntity("Snacks"));
  
  Set<OrderEntity> orders1 = new HashSet<>();
  orders1.add(new OrderEntity("Egg"));
  orders1.add(new OrderEntity("Bread"));
  orders1.add(new OrderEntity("Snacks"));
  
  System.out.println("Saving Recordings... ");
  long customerId1 = mainApp.saveRecords("Sushil Kumar", "1234567890", orders);
  long customerId2 = mainApp.saveRecords("Vijay Kumar", "1234567891", orders1);
  
  System.out.println("Displaying Records...");
  mainApp.getRecords();
  
  System.out.println("Updating Recordings... ");
  mainApp.updateRecord(customerId1, "9876543210");
  
  System.out.println("Displaying Records...");
  mainApp.getRecords();
  
  System.out.println("Deleting 'Vijay Kumar' Record...");
  mainApp.deleteRecord(customerId2);
  
  System.out.println("Displaying Records...");
  mainApp.getRecords();
 }
 
 private long saveRecords(String customerName, String customerPhone, Set<OrderEntity> orders) {

  Transaction transaction = null;
  Session session = sessionFactory.openSession();
  long customerId = 0;
  
  try {
   transaction = session.beginTransaction();
   CustomerEntity customer = new CustomerEntity(customerName, customerPhone);
   customer.setOrders(orders);
   customerId = (long) session.save(customer);
   
   transaction.commit();
   
  } catch(HibernateException e) {
   e.printStackTrace();
  } finally {
   session.close();
  }
  return customerId;
 }
  
 private void getRecords() {
  
  Transaction transaction = null;
  Session session = sessionFactory.openSession();
  try {
   
   transaction = session.beginTransaction();
   
   CriteriaBuilder builder = session.getCriteriaBuilder();
   CriteriaQuery<CustomerEntity> criteria = builder.createQuery(CustomerEntity.class);
   Root<CustomerEntity> customerRoot = criteria.from(CustomerEntity.class);
   List<CustomerEntity> customers = session.createQuery(criteria.select(customerRoot)).getResultList();
   
   // Printing Records to Console
   for(CustomerEntity customer : customers) {
    for(OrderEntity order : customer.getOrders()) {
     System.out.println(customer.getCustomerId()+" | "+customer.getCustomerName()+" | "+customer.getCustomerPhone()+" | "+order.getOrderName());
    }
   }
   transaction.commit();
   
  } catch(HibernateException e) {
   e.printStackTrace();
  } finally {
   session.close();
  }
 }
 
 private void updateRecord(long customerId, String customerPhone) {

  Transaction transaction = null;
  Session session = sessionFactory.openSession();
  
  try {
   transaction = session.beginTransaction();
   CustomerEntity customer = session.get(CustomerEntity.class, customerId);
   customer.setCustomerPhone(customerPhone);
   
   session.update(customer);
   transaction.commit();
   
  } catch(HibernateException e) {
   e.printStackTrace();
  } finally {
   session.close();
  }
 }
 
 private void deleteRecord(long customerId) {

  Transaction transaction = null;
  Session session = sessionFactory.openSession();
  
  try {
   transaction = session.beginTransaction();
   CustomerEntity customer = session.get(CustomerEntity.class, customerId);
   session.delete(customer);
   transaction.commit();
   
  } catch(HibernateException e) {
   e.printStackTrace();
  } finally {
   session.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

Customer and Orders table after running the project successfully


Click on the below button to download this project

Download Project



SHARE
    Blogger Comment
    Facebook Comment

4 comments: