Search code examples
javahibernatejdbcbatch-processingcriteria

How to create batch update in hibernate with entity manager and criteria?


All I tried is to create a batch update in bd, but faced with a problem. I read many articles and all of them manually manage a session, I don't want to do it. How I can create batch update for my entities I write the following code:

@Transactional(propagation = Propagation.REQUIRED)
public void update(List<MyClass> objects) {
    for (MyClass o: objects) {
        getEntityManager().merge(o);
    }
}

Also, I added the following properties hibernate.jdbc.batch_size=32

Where my mistake?


Solution

  • First, in case "MyClass" is a versioned entity, then you need to enable the following property:

    hibernate.jdbc.batch_versioned_data=true
    

    Now, you did not mention if the list "objects" contains hibernate managed or detached objects. If these are not detached instances, then merge is not necessary as hibernate already knows about the changes that happened to the entities.

    Finally, you just need to flush the session using getEntityManager().flush(); This should flush all the changes to the database and hibernate should do its batching magic.

    This guide about batching should be helpful: https://vladmihalcea.com/how-to-batch-insert-and-update-statements-with-hibernate/