简体   繁体   中英

Calling Session.flush in Hibernate session bulk update

I have a list of object, for each object I am executing Session.update(), when should I call Session.flush()? After the list complete its iteration or after each update? The code segment is:

public void updateUserAssignmentInfo(final long itemId) {
    getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.flush();
            session.setCacheMode(CacheMode.IGNORE);
            List<UserAssignmentInfo> userAssignmentInfos = session.createQuery("from UserAssignmentInfo as userAssignmentInfo where userAssignmentInfo.itemId = " + itemId).list();
            if (userAssignmentInfos.size() == 0) {
                return null;
            }
            for (UserAssignmentInfo userAssignmentInfo : userAssignmentInfos) {
                userAssignmentInfo.setIsCurrentlyAssigned(false);
                session.update(userAssignmentInfo);
                // should I call flush here?
            }
            session.flush(); // or here?
            return null;
        }
    });
}

Usually you don't need to call flush() at all - Hibernate automatically flushes session before executing queries and before transaction commit. Manual flush() should be used only if you have some reasons to override default behaviour.

Moreover, in this scenario you even don't need to call update() - since entities was loaded inside the same transaction, changes in their state will be propagated to the database automatically.

The latter one.

Also please have a look at: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/batch.html

Calling session flush at the end will cause that you have higher probability that query will be only soft parsed by database.

In bulk operations, it might make sense to set the flush mode to manual. reason being if you are doing let us say 30k updates and there is select before each update to validate some conditions, hibernate will flush the session before every query, even read. This will make the performance to degrade. We have seen this behavior and by turning Flush mode to manual , an improvement in performance was seen

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