Introduction
Hibernate is a framework of Java that allows Object-relational mapping. As it is open-source and free to download, it is highly available and accessible. Its fast performance, database independency, automatic table creation, and simplification capability have led to its immense utility and popularity. Development costs and time have been reduced since the launch of Hibernate because it provides a way to handle persistent data. By the term persistent data, we mean infrequently accessed data that is unlikely to be modified.

Hibernate Batch Processing
Hibernate Batch Processing consists of two terms, that is, Hibernate and Batch Processing. Before jumping directly into Hibernate Batch Processing, let us understand both the terms separately. We have already seen what Hibernate is in the introduction above. Now, in the next paragraph, we will see what batch processing is.
By the term batch, the first thing that comes to mind is a group. This group can be a collection of things that are common in nature. Here, batch in batch processing means a group of queries. Instead of executing a single query every other time, we are allowed to execute a bunch of queries known as batches. It makes the performance faster because multiple statements are sent to the database at once. In this way, the overhead communication is reduced by a significant amount. Since the communication with the database is not frequent, this leads to faster performance.
Combining these two, we understand that Hibernate Batch Processing is normal batch processing, but in Hibernate framework.
Project Creation Example
To create a Java project based on Maven using Eclipse IDE, you need to follow the steps below.
- In the Eclipse IDE, from the menu tab, select the file menu and click on the New option. Then, select the Maven Project option.
- Now, the Maven Project window will be opened. In that window, you will be asked to select the Project Location. There will be three options, and from those options, you can select any option of your choice and proceed.
- Then, you will be asked to enter the group and the artifact id. Input the details as per the requirement. The version number will be selected by default.
- Click on Finish, and the creation of a maven project is done.
Application Building
To develop an application, you need to follow the steps explained below.
- Creation of Database and Table
Open the MySQL terminal, and execute the MySQL code below. The database name will be Student and the table name will be Marks.
CREATE DATABASE IF NOT EXISTS Student;
USE Student;
DROP TABLE IF EXISTS Marks;
CREATE TABLE Marks (
product_id int(20) NOT NULL AUTO_INCREMENT,
product_code varchar(255) DEFAULT NULL,
PRIMARY KEY (product_id)
);
- Now, we are supposed to specify only two dependencies, that is, MySQL Connector and Hibernate Core. Rest other dependencies will be specified automatically by Maven.
- The required Java classes will be created after that. You need to create a Model class as well as a Utility class.
Implementation of Model Class
Consider the POJO class below and add the following code to implement the Model Class.
package com.jcg.hibernate.batch.processing;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "product")
public class Product {
@Id
@Column(name = "product_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long productId;
@Column(name = "product_code")
private String productCode;
public Product() { }
public Product(String productCode) {
this.productCode = productCode;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Implementation of Utility Class
The Utility Class will create the SessionFactory for the Hibernate Configuration File and will interact with the database so that it can perform batch operations. Methods available with the session object such as flush() and clear() will be used in a way that Hibernate keep writing records instead of caching them.
package com.jcg.hibernate.batch.processing;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
@SuppressWarnings("unchecked")
public class AppMain {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
private static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void main(String[] args) {
System.out.println(".......Hibernate Batch Processing Example.......\n");
try {
sessionObj = buildSessionFactory().openSession();
sessionObj.beginTransaction();
int batchSize = 30, totalRecords = 100;
// - - - - - - - - - - - - - - Hibernate/JPA Batch Insert Example - - - - - - - - - - - - //
for (int i = 0; i < totalRecords; i++) { Product product = new Product("Product " + i); sessionObj.save(product); if (i % batchSize == 0 && i > 0) {
// Flush A Batch Of Inserts & Release Memory
sessionObj.flush();
sessionObj.clear();
}
}
System.out.println("\n.......Records Saved Successfully To The Database.......\n");
// - - - - - - - - - - - - - - Hibernate/JPA Batch Update Example - - - - - - - - - - - - //
String sqlQuery = "FROM Product";
List productList = sessionObj.createQuery(sqlQuery).list();
for (int j = 0; j < productList.size(); j++) { Product projectObj = productList.get(j); projectObj.setProductCode("New Product " + j); sessionObj.update(projectObj); if (j % batchSize == 0 && j > 0) {
// Flush A Batch Of Updates & Release Memory
sessionObj.flush();
sessionObj.clear();
}
}
System.out.println("\n.......Records Updated Successfully In The Database.......\n");
// Committing The Transactions To The Database
sessionObj.getTransaction().commit();
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
System.out.println("\n.......Transaction Is Being Rolled Back.......");
sessionObj.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
Hibernate Configuration File
Now when you are done with creating applications, you need to create a Hibernate Configuration file. Once that has been created, you have to add database configuration and mapping details using the following code.
<?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>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- Batching Size Settings -->
<property name="hibernate.jdbc.batch_size">30 </property>
<property name="hibernate.order_inserts">true </property>
<property name="hibernate.order_updates">true </property>
<property name="hibernate.jdbc.batch_versioned_data">true </property>
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="com.jcg.hibernate.batch.processing.Product" />
</session-factory>
</hibernate-configuration>
The Application is now ready to run. Once you have checked that the application is running well, you can go for Project Demo to see the working of the project.





