The Wayback Machine - https://web.archive.org/web/20240930183604/https://www.geeksforgeeks.org/hibernate-batch-processing/
Open In App

Hibernate – Batch Processing

Last Updated : 22 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hibernate is storing the freshly inserted objects in the second-level cache. Because of this, there is always the possibility of OutOfMemoryException when  Inserting more than one million objects. But there will be situations to inserting huge data into the database. This can be accomplished by batching in hibernate.

Note: hibernate.jdbc.batch_size has to be set and it is an integer between 10 and 50. If zero or negative value is set, then it disables batching.

Let us use the JPA @TableGenerator annotation to generate the unique key for the entity. As we are not sure of how many records were inserted because of the batch, the IDENTITY generator is disabled by Hibernate.

Example Project 

Project Structure:

 

This is a maven-driven project

pom.xml

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                       http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.gfg.hibernate.batch</groupId>
   <artifactId>hibernate-batching-example</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <properties>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
   </properties>
<dependencies>
   <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.15.Final</version>
   </dependency>
   <!-- mysql connector dependency -->
   <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.34</version>
   </dependency>
   <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.0</version>
   </dependency>
 
   <!--Log4j2 API -->
   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.11.0</version>
   </dependency>
   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.11.0</version>
   </dependency>
</dependencies>
</project>


For logging purposes, we are using log4j2.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
   <Appenders>
      <!-- Console Appender -->
      <Console name="Console" target="SYSTEM_OUT">
         <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
      </Console>
   </Appenders>
   <Loggers>
      <!-- Log everything in hibernate -->
      <Logger name="org.hibernate.engine.jdbc.batch.internal.BatchingBatch" level="debug" additivity="false">
         <AppenderRef ref="Console" />
      </Logger>
      <Root level="error">
         <AppenderRef ref="Console" />
      </Root>
   </Loggers>
</Configuration>


Let us see the important files of the application. Let’s start with the entity class

Product.java

Java




import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
 
@Entity
public class Product {
 
    @Id
    @TableGenerator(name = "PRODUCT_SEQ")
    // As we are doing batch insert, using TableGenerator,
    // unique key is determined
    @GeneratedValue(strategy = GenerationType.TABLE,
                    generator = "PRODUCT_SEQ")
    // data members of product
    private Long id;
 
    private String productName;
    private String productBrand;
    private int price;
    // Getter and setters
 
    public Long getId() { return id; }
 
    public void setId(Long id) { this.id = id; }
 
    public String getProductName() { return productName; }
 
    public void setProductName(String productName)
    {
        this.productName = productName;
    }
 
    public String getProductBrand() { return productBrand; }
 
    public void setProductBrand(String productBrand)
    {
        this.productBrand = productBrand;
    }
 
    public int getPrice() { return price; }
 
    public void setPrice(int price) { this.price = price; }
    // This is essentially required to avoid exceptions
    public Product() {}
}


Let us see the main Util class

HibernateUtil.java

Java




import com.gfg.hibernate.batch.entity.Product;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
 
public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;
 
    public static SessionFactory getSessionFactory()
    {
        if (sessionFactory == null) {
            try {
                StandardServiceRegistryBuilder
                    registryBuilder
                    = new StandardServiceRegistryBuilder();
 
                // Configuration properties
                Map<String, Object> settings
                    = new HashMap<>();
 
                settings.put(Environment.DRIVER,
                             "com.mysql.jdbc.Driver");
 
                settings.put(
                    Environment.URL,
                    "jdbc:mysql://localhost:3306/geeksforgeeks?serverTimezone=UTC");
                // Specify mySQL credentials here
                settings.put(Environment.USER, "root");
                settings.put(Environment.PASS, "admin");
 
                settings.put(Environment.HBM2DDL_AUTO,
                             "update");
                // Set JDBC batch size. It can be set
                // between 10 and 50
                settings.put(
                    Environment.STATEMENT_BATCH_SIZE, 50);
 
                registryBuilder.applySettings(settings);
                registry = registryBuilder.build();
 
                MetadataSources sources
                    = new MetadataSources(registry);
               
                // This entity class Product is going to be
                // used for batch insert or update
                sources.addAnnotatedClass(Product.class);
                Metadata metadata
                    = sources.getMetadataBuilder().build();
 
                sessionFactory
                    = metadata.getSessionFactoryBuilder()
                          .build();
            }
            catch (Exception e) {
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(
                        registry);
                }
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
 
    public static void shutdown()
    {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(
                registry);
        }
    }
}


Let us see how to batch insert can be happened via 

InsertProductBatchExample.java

Java




import com.gfg.hibernate.batch.entity.Product;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
public class InsertProductBatchExample {
    public static void main(String[] args)
    {
        Session session = null;
        Transaction transaction = null;
        // Setting zero or negative number will disable the
        // batching.
        int batchSize
            = 10; // As of now, it is hardcoded to 10
        try {
            session = HibernateUtil.getSessionFactory()
                          .openSession();
            transaction = session.beginTransaction();
            // Here as a sample 100 items are inserted, but
            // it can be changed as per user choice
            for (long idx = 1; idx <= 100; idx++) {
                Product product = new Product();
                // We can use this as sample. Please change
                // according to the requirement
                product.setProductName("Product" + idx);
                product.setProductBrand("A");
                product.setPrice((int)idx * 10);
                session.save(product);
                if (idx > 0
                    && idx % batchSize
                           == 0) { // Keep on doing this
                                   // step in order to
                                   // continue and avoid
                                   // exceptions
                    session.flush();
                    session.clear();
                }
            }
            transaction.commit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session != null) {
                session.close();
            }
        }
 
        HibernateUtil.shutdown();
    }
}


On execution of the above program, in the console, we can able to see  as 

 

Let us check the same with MySQL output as well

 

Now let us see the same for updates as well.

UpdateProductBatchExample.java

Java




import com.gfg.hibernate.batch.entity.Product;
import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
public class UpdateProductBatchExample {
    public static void main(String[] args)
    {
        Session session = null;
        Transaction transaction = null;
        // As we are going to do bulk operations, we need
        // ScrollableResults
        ScrollableResults scrollableResults = null;
        // Setting zero or negative number will disable the
        // batching.
        int batchSize = 10; // It can be between 10 and 50.
        try {
            session = HibernateUtil.getSessionFactory()
                          .openSession();
            transaction = session.beginTransaction();
            scrollableResults
                = session
                      .createQuery(
                          "from Product") // Query the table
                      .setCacheMode(CacheMode.IGNORE)
                      .scroll(
                          ScrollMode
                              .FORWARD_ONLY); // We have to
                                              // get all
                                              // records
            int count = 0;
            int price = 1;
            while (scrollableResults.next()) {
                Product product
                    = (Product)scrollableResults.get(0);
                product.setPrice(
                    price
                    + (price
                       * 10)); // update the price, this is
                               // just a sample
                price += 1;
                if (++count % batchSize
                    == 0) { // This is much required
                    session.flush();
                    session.clear();
                }
            }
            transaction.commit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (scrollableResults != null) {
                scrollableResults.close();
            }
            if (session != null) {
                session.close();
            }
        }
        HibernateUtil.shutdown();
    }
}


 

MySQL output is as follows:

 

Conclusion

By using “hibernate.jdbc.batch_size” we can enable batch processing in hibernate session.flush() and session.clear() should be periodically done to avoid exceptions and it is a good practice essentially required for batch processing.



Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, batch processing is used to read and write data in bu
7 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Hibernate - Web Application
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes. Tools and
9 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate - Criteria Queries
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. To get the data available in RDBMS tables, Hibernate fol
12 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Types of Mapping
Hibernate is a Java framework that simplifies the development of Java applications to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. There are different relations that we maintain to establish a link betw
2 min read
Hibernate - Many-to-Many Mapping
In RDBMS, we can see a very common usage of parent-child relationships. It can be achieved in Hibernate via One-to-many relationshipMany-to-one relationshipOne-to-one relationshipMany-to-many relationship Here we will be discussing how to perform Hibernate - Many-to-Many mappings. Below are the example tables to demonstrate Many-to-Many mappings as
12 min read
Hibernate - Interceptors
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling. The Interceptors 1.1 specification is part of the final release of JSR 318, E
6 min read
Hibernate - Table Per Concrete Class Using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
7 min read
Hibernate - Logging By Log4j Using Properties File
Apache log4j is a java-based logging utility. Apache log4j role is to log information to help applications run smoothly, determine what’s happening, and debug processes when errors occur. log4j may logs login attempts (username, password), submission form, and HTTP headers (user-agent, x-forwarded-host, etc.) into the log file or database. Apache l
2 min read
Hibernate - Many-to-One Mapping
Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and with a server also. It is a top layer of JDBC, JTA,
5 min read
Hibernate - Logging by Log4j using xml File
The process of Hibernate Logging by Log4j using an XML file deals with the ability of the computer programmer to write the log details of the file he has created by executing it permanently. The most important tools in Java language like the Log4j and Log back frameworks. These frameworks in Java language help the programmer to install and initiate
5 min read
Article Tags :
Practice Tags :