Hibernate MANUAL 刷新模式的行为类似于 AUTO [英] Hibernate MANUAL flushmode behaves like AUTO

查看:46
本文介绍了Hibernate MANUAL 刷新模式的行为类似于 AUTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 HQL 更新表,并希望将 Flush 模式设置为 MANUAL.我尝试了 2 种方法.

I'm trying to update a table using HQL and want to set the Flush mode to MANUAL. I've tried 2 approaches.

// Update user via session
em.unwrap(Session.class).createQuery("update User u set u.numRecords =:numRecords where u.id = 1")
    .setParameter("numRecords", new Random().nextInt(1234567))
    .setHibernateFlushMode(FlushMode.MANUAL)
    .executeUpdate();

// Update user via entity manager.
Query query = em
    .createQuery("update User u set u.numRecords =:numRecords where u.id = 1")
    .setParameter("numRecords", new Random().nextInt(1234567));
((QueryImpl) query).setFlushMode(FlushMode.MANUAL).executeUpdate();

我的调用者按如下方式调用这 2 个方法 -

My caller is calling these 2 methods as follows -

@Transactional
public void foo() {
    userRepository.updateUserViaSession();
    userRepository.clear();
}

@Transactional
public void foo2() {
    userRepository.updateUserViaEntityManager();
    userRepository.clear();
}

实体 -

@Entity
@Table(name = "users")
public class User {
    @Id
    private Long id;
    private String email;
    private int numRecords;
    private int numAllowedRecords;
}

问题是,当我调用 foo() 或 foo2() 时,Hibernate 会立即刷新更新,而不是等待我显式调用 flush().为什么会这样?

The problem is that when I call either foo() or foo2(), Hibernate flushes the update immediately instead of waiting for me to explicitly call flush(). Why is this the case?

推荐答案

FlushMode 不是这样工作的.

在查询上设置 FlushMode 控制是否应该在查询执行之前刷新持久化上下文.它对何时查询执行没有影响.JPA 总是立即执行查询.

Setting the FlushMode on a query controls whether or not the persistence context should be flushed before query execution. It has no effect on when the query executes. JPA always executes queries immediately.

覆盖 FlushMode 在您不希望查询看到在当前上下文中所做的更改时很有用.默认情况下,JPA 假设到目前为止所做的所有更改都应该被查询看到,因此它会在执行之前刷新上下文以确保这一点.

Overriding the FlushMode is useful when you don't want the query to see changes made within the current context. By default, JPA assumes all changes made so far should be seen by the query, and so it flushes the context just before the execution to ensure that.

这篇关于Hibernate MANUAL 刷新模式的行为类似于 AUTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆