Hibernate Batch Processing - Hibernate

What is Hibernate Batch Processing?

Consider a condition when you need to upload a large number of records into your database using Hibernate. Following is the code clip to reach this using Hibernate:

Since by default, Hibernate will cache all the persisted objects in the session-level cache and finally your application would fall over with an OutOfMemoryException somewhere around the 50,000th row. You can resolve this predicament if you are using batch processing with Hibernate.

To use the group processing feature, first set hibernate.jdbc.batch_size as batch size to a numeral either at 20 or 50 depending on object size.

This will tell the hibernate container that every X rows to be inserted as batch. To apply this in your code we would need to do small alteration as follows:

Above code will work well for the INSERT operation, but if you are willing to create UPDATE operation then you can complete using the following code:

Batch Processing Example:

Let us change configuration file as to add hibernate.jdbc.batch_size property:

Consider the following POJO Employee class:

Let us make the following EMPLOYEE table to accumulate Employee objects:

Following will be mapping case to map Employee substance with EMPLOYEE table.

At last, we will create our application class with the main () method to run the application where we will use flush () and clear () methods accessible with Session object so that Hibernate keep script these records into the database in its place of caching them in the memory.

Compilation and Execution:

Here are the steps to compile and run the above mentioned application. Construct sure you have set PATH and CLASSPATH exactly before arranged for the compilation and implementation.

  • Create hibernate.cfg.xml configuration file as explained above.
  • Create Employee.hbm.xml mapping file as shown above.
  • Create Employee.java source file as shown above and compile it.
  • Create ManageEmployee.java source file as shown above and compile it.
  • Execute ManageEmployee binary to run the program which will create 100000 records in EMPLOYEE table.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Hibernate Topics