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
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;
update(Iterator<Entity> entities)
codein 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
@Transactional
annotation on your save(Iterable<Entity> entities)
method. make sure you have transactional annotation support in the Spring Context tooIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With