简体   繁体   English

在Hibernate会话批量更新中调用Session.flush

[英]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()? 我有一个对象列表,对于我正在执行Session.update()的每个对象,何时应调用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. 通常,您根本不需要调用flush() -Hibernate在执行查询之前和事务提交之前自动刷新会话。 Manual flush() should be used only if you have some reasons to override default behaviour. 仅当出于某些原因要覆盖默认行为时,才应使用手动flush()

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. 而且,在这种情况下,您甚至不需要调用update() -由于实体是在同一事务中加载的,因此它们状态的更改将自动传播到数据库中。

The latter one. 后者。

Also please have a look at: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/batch.html 还请看看: 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. 原因是如果您要进行3万次更新,并且每次更新之前都有选择以验证某些条件,那么休眠将在每次查询(甚至读取)之前刷新会话。 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 我们已经看到了这种现象,并且通过将“刷新”模式设置为手动,可以看到性能的提高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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