Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Hibernate bulk/batch update in Spring MVC

I am new to Spring MVC and not much idea with JPA as well. all I want to do is to update a list of records and its working well when I loop through the list and call update on DAO.

But I dnt want to perform 100 update/insert operations or DB round trips.

Could any one please show me how to update around 100 records with batch update instead of doing the following:

Controller:
    List<MyEntity> list = form.getList();
    for(MyEntity e : list){
        dao.update(e);
    }

Dao:
    public T update(T entity){
         entityManager.merge(entity);        
    }

Is it possible, if someone could provide me a simple way to perform batch update. I would really appreciate if I get as much explaination as possible.

Thanks

like image 849
user22197 Avatar asked Jul 13 '13 00:07

user22197


1 Answers

what you've got is pretty much the standard way of updating multiple rows via JPA. event spring-data-jpa that exposes save(Iterable<T> items) just loops over the Iterator under the covers. here's another question that is answered very nicely on the options, but in short, you're on the right path with the alternative being to formulate and execute the update statement yourself.

update: executing in a single transaction may increase performance as you only have the transaction overhead once. you also get the scenario where if one of the updates fail, any previous ones are rolled back too. (so, potentially you lose all the 'work' from previous updates - you may or may not want that)

also, be aware of the transaction manager type you're using (e.g. JTA or JPA) and the JPA implementation (e.g. Hibernate) as sometimes they don't play nice together.

so, in your DAO code you may want to do this;

  • add an overload update(Iterator<Entity> entities) code
  • in that code do something like the following;

    entityManager.getTransaction().begin();//start the transaction

    for (Entity entity : entities) {

        entityManager.merge(entity);//update an entity
    

    }

    entityManager.getTransaction().commit();//complete the transaction

  • or you can you use the @Transactional annotation on your save(Iterable<Entity> entities) method. make sure you have transactional annotation support in the Spring Context too
like image 158
incomplete-co.de Avatar answered Oct 17 '22 12:10

incomplete-co.de