Hibernate Batch Update Using HQL Query

I am using Hibernate for my ORM layer. I am trying to run a HQL query package in a single transaction (I cannot use session.update). The problem is that even transaction.commit () is at the end of the loop, update requests are triggered one by one. Is there a way to run multiple HQL queries in a single transaction?

public void updateItems() { t = session.beginTransaction(); for (int i = 0; i < itemList.size(); i++) { Query q = createUpdateQuery(session, itemList.get(i)); q.executeUpdate(); //updating one by one, and not waiting for transaction commit } t.commit(); } Query createUpdateQuery(Session session, Item item) { Query q = session.createQuery( "Update Item i set i.notes=:notes, i.time=:time, i.counter=:counter, i.status=:status Where i.id=:id and i.time=:time"); q.setParameter("time", item.getTime()); q.setParameter("status", item.getStatus()); q.setParameter("notes", item.getNotes()); q.setParameter("id", item.getId()); return q; } 

Appreciate any help.

+5
source share
1 answer

You use a database transaction to register all of your statements, but I think you want to use batch updates .

Just add the following configuration property:

 <property name="hibernate.jdbc.batch_size" value="10"/> 

However, I think you should use Hibernate to control insert / update / delete operations, since you should focus only on state transitions of the object . a dirty checking mechanism can automatically detect objects that have been changed, and Hibernate can generate an update statement for you, which is much more convenient.

+2
source

Source: https://habr.com/ru/post/1247487/


All Articles