Batch insert or update in java with hibernate
Posted By : Md Imroz Alam | 27-Jun-2018
When we want to insert or update a
we do batch insertion or
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.
Request for Proposal
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.