Batch insert or update in java with hibernate

Posted By : Md Imroz Alam | 27-Jun-2018

When we want to insert or update a lot of entries with performance improvements.

we do batch insertion or update in a database.

We need to add following properties in spring-boot application

spring.jpa.properties.hibernate.jdbc.batch_size=20
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true

Below are the sample example for batch insert 

@Autowired
EntityManagerFactory entityManagerFactory;

int batchSize=20;
EntityManager entityManager = null;
EntityTransaction txn = null;
entityManager = entityManagerFactory.createEntityManager();
txn = entityManager.getTransaction();
txn.begin();
try{
for(int i=0;i<1000;i++){
if(i % batchSize == 0 && i > 0) {
entityManager.flush();
entityManager.clear();
txn.commit();
         }
Employee newEmp=new Employee();
newEmp.setName("John");
newEmp.id(1);
entityManager.persist(newMarketData);
}

} catch (RuntimeException e) {
LOGGER.error("Exception on batch insert : " + e.getMessage());
if (txn != null && txn.isActive())
txn.rollback();
} catch (Exception e) {
LOGGER.error("error batch insertion: " + e.getMessage());
} finally {
if (entityManager != null) {
entityManager.close();
}
}
When we need to update existing record in a batch
 
Instead of entityManager.persist use entityManager.merge(existingObject)
 
Thanks
I hope this will be helpful.

About Author

Author Image
Md Imroz Alam

Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.

Request for Proposal

Name is required

Comment is required

Sending message..