gpt4 book ai didi

java - FlushMode.COMMIT 的工作原理

转载 作者:行者123 更新时间:2023-12-01 12:30:40 25 4
gpt4 key购买 nike

根据 Session.setFlushMode(FlushMode)我们可以将 FlushMode 设置为 session 。现在我正在尝试测试Flushmode.COMMIT如何模式适用于一个小例子。

我创建了一个名为 Cat 的实体,只有 2 个属性 idname。现在这是我正在测试的代码:

    Session session = getSession();
session.setFlushMode(FlushMode.COMMIT);
Transaction tx = session.beginTransaction();
Cat cat = (Cat) session.get(Cat.class, 1);
cat.setName(name);
session.flush();
//tx.commit();
session.close();

从日志中我可以看到,当执行 session.flush() 行时,hibernate 将向数据库发出 JDBC 更新调用,如下所示:

Hibernate: update Cat set name=? where id=?

当我将 FlushMode 设置为 COMMIT 时,我期望仅当我说 tx.commit() 时才会执行 update 查询,但刷新发生在session.flush()。有人可以解释一下为什么会这样吗?

最佳答案

注意 Session#flush() 的 Javadoc。

Force this session to flush. Must be called at the end of a unit of work, before committing the transaction and closing the session (depending on flush-mode, Transaction.commit() calls this method).

FlushMode#MANUAL的javadoc

The Session is only ever flushed when Session.flush() is explicitly called by the application. This mode is very efficient for read only transactions.

设置FlushMode只是定义flush()何时自动发生(除了MANUAL)。如果您自己手动调用 flush(),则您将覆盖该行为。

关于java - FlushMode.COMMIT 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com