简体   繁体   中英

Hibernate batch update using HQL Query

I'm using Hibernate for my ORM layer. I'm try to run batch of HQL queries in one transaction (I cannot use session.update). The issue is that even the transaction.commit() is at the end of the loop, the update queries run one by one. Is there a way to run multiple HQL queries in one 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.

You are using a database transaction to enroll all 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"/>

Even so, I think you should use Hibernate to manage the insert/update/delete statements, as you should only focus on entity state transitions . The dirty checking mechanism can automatically detect entities that have been modified, and Hibernate can generate the update statement for you, which is much more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM