java - 如何配置 Hibernate 以立即应用所有保存、更新和删除?

标签 java database hibernate

如何配置 Hibernate在 session 执行每个操作后立即将所有保存、更新和删除应用到数据库服务器?默认情况下,Hibernate 将所有保存、更新和删除操作排入队列,并仅在 flush() 操作、提交事务或关闭发生这些操作的 session 后才将它们提交给数据库服务器.

立即刷新数据库“写入”操作的一个好处是,程序可以在它们发生的代码块中捕获和处理任何数据库异常(例如 ConstraintViolationException)。使用延迟或自动刷新,这些异常可能会在导致 SQL 操作的相应 Hibernate 操作之后很长时间内发生。

更新:

根据接口(interface)的 Hibernate API 文档 Session ,在 session 结束之前捕获和处理数据库异常的好处可能根本没有好处:“如果 session 抛出异常,则必须回滚事务并丢弃 session 。 session 的内部状态可能不是异常发生后与数据库一致。"

那么,用 try-catch block 围绕“立即”Hibernate session 写操作的好处可能是在异常发生时立即捕获并记录异常。立即清除这些操作还有其他好处吗?

最佳答案

How can I configure Hibernate to apply all saves, updates, and deletes to the database server immediately after the session executes each operation?

据我所知,Hibernate 没有为此提供任何便利。但是,看起来 Spring 可以,您可以进行一些数据访问操作 FLUSH_EAGER通过转动他们的 HibernateTemplate分别HibernateInterceptor到那个刷新模式(source)。

但我强烈建议您仔细阅读javadoc(我会回来的)。

By default, Hibernate enqueues all save, update, and delete operations and submits them to the database server only after a flush() operation, committing the transaction, or the closing of the session in which these operations occur.

关闭 session 不会刷新。

One benefit of immediately flushing database "write" operations is that a program can catch and handle any database exceptions (such as a ConstraintViolationException) in the code block in which they occur. With late or auto-flushing, these exceptions may occur long after the corresponding Hibernate operation that caused the SQL operation

首先,DBMS 会根据插入(或更新)或后续提交(这称为立即或延迟约束)再次出现约束违规而有所不同。所以没有保证,您的 DBA 甚至可能不希望立即约束(尽管这应该是默认行为)。

其次,我个人认为立即冲洗的弊端多于好处,正如 FLUSH_EAGER 的 javadoc 中以白纸黑字解释的那样。 :

Eager flushing leads to immediate synchronization with the database, even if in a transaction. This causes inconsistencies to show up and throw a respective exception immediately, and JDBC access code that participates in the same transaction will see the changes as the database is already aware of them then. But the drawbacks are:

  • additional communication roundtrips with the database, instead of a single batch at transaction commit;
  • the fact that an actual database rollback is needed if the Hibernate transaction rolls back (due to already submitted SQL statements).

相信我,增加数据库往返次数和减少语句批处理会导致性能显着下降

另请记住,一旦遇到异常,除了丢弃 session 外,您无能为力。

总而言之,我很高兴 Hibernate 对各种操作进行排队,我当然不会使用此 EAGER_FLUSH flushMode 作为一般设置(但可能仅用于实际需要 eager 的特定操作(如果有的话)。

关于java - 如何配置 Hibernate 以立即应用所有保存、更新和删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3943366/

相关文章:

java - Selenium Webdriver java : click on a checkbox

java - 为什么我的应用程序无法从我的 API 读取 JSON?

java - 如何显示打印对话框

hibernate ,更改标识符/主键

java - 将 .class 文件转换回文本

java - 如何以 FIFO 顺序从文件夹中轮询文件

php - mysql查询按上次发帖排序

java - 使用 Spring 和 Hibernate 将异常记录到数据库

java - 如何在 Hibernate 模板中执行更新(命名查询)?

spring - 如何使用 Spring Hibernate 在不使用 spring.jpa.hibernate.ddl-auto 的情况下自动创建审计表