Table of contents
1.
Introduction
2.
Hibernate Batch Processing
2.1.
Project Creation Example
2.2.
Application Building
2.3.
Hibernate Configuration File
3.
Frequently Asked Questions
3.1.
What are the advantages of Hibernate over JDBC?
3.2.
Name the different functionalities supported by Hibernate.
3.3.
What does one to one association mean?
3.4.
How many key components are there in a Hibernate Configuration Object? Name them.
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Hibernate Batch Processing

Author Rupal Saluja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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. 

logo of hibernate

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.

Frequently Asked Questions

What are the advantages of Hibernate over JDBC?

The prominent advantages of Hibernate over JDBC are listed below.

  • Overcomes databases dependencies.
  • Code portability.
  • Strengthening of object-level relationship.
  • Less expensive.
  • Reduced length of code.

Name the different functionalities supported by Hibernate.

Several different functionalities supported by Hibernate are mentioned below.

  • Object-Relational Mapping
  • Database independent HQL
  • Auto DDL operations
  • Automated Primary Key generation
  • No compulsory exception handling

What does one to one association mean?

A one-to-one mapping means that a single row from one table can be related to only one row from the other table.

How many key components are there in a Hibernate Configuration Object? Name them.

There are two key components in a Hibernate Configuration Object. These are, namely:

  • Database Connection
  • Class Mapping Setup

Conclusion

This article will discuss Hibernate Batch Processing. We will use an example to illustrate the notion of Hibernate Set Mapping. 

To check out our hibernate interview questions article, visit Hibernate Interview Questions 2022 | Part 1 - Coding Ninjas Coding Ninjas Studio

I hope you would have gained a better understanding of these topics now!

Are you planning to ace the interviews of reputed product-based companies like AmazonGoogleMicrosoft, and more? 

Attempt our Online Mock Test Series on Coding Ninjas Studio now.

Happy Coding!

Live masterclass