java - 什么时候不使用 EntityManager.flush()?

标签 java jpa eclipselink entitymanager flush

为了同步和检索数据库生成的 ID,我不得不在几个地方调用 EntityManager.flush()

抛开性能影响,是否有理由调用flush()

换句话说,如果我的 (DAO, ...) 方法的调用者执行/不执行 flush(),是否有任何可观察到的差异?

我的场景是在支持我们的 JPA 开发人员的框架上下文中。我会提供一些功能,这些功能可能需要也可能不需要 flush() 在调用层次结构的深处。这些函数的用户是否必须知道是否/何时发生刷新,或者它是一个私有(private)实现细节,对调用者没有明显影响?

最佳答案

调用 flush() 将持久性上下文与数据库同步。这主要是必需的 - 如果需要查询命中(通过 JPQL 等)。

稍后在对数据库的调用堆栈中,如果持久化上下文包含其状态可能受查询结果影响的任何对象的脏值,则需要同步这些对象。事实上默认FlushModeType对于 JPA 查询是 AUTO

When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query or TypedQuery object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query or TypedQuery object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query. The persistence provider implementation may achieve this by flushing those entities to the database or by some other means.

因此,只要您通过对象的状态而不是 JPA 查询来查询对象,并且这些查询的结果不依赖于脏状态,那么调用 flush 对性能不利,因为它涉及重复的脏状态检查,而不仅仅是在提交时。

@Adams 提到了他使用 OpenJPA 的经历,其中 flush 几乎不会破坏任何东西,所以我猜不同的实现在这里存在问题。

关于java - 什么时候不使用 EntityManager.flush()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709673/

相关文章:

java - 如何在 Spring Integration DSL 中将对象放入 Gemfire 缓存?

jpa - HyperJaxb3 还在维护吗?

java - 从 JPA 2.0 中的实体对象中提取主键?

java - 拆分字符串在 java 中不起作用无法导入 `split`

java - 对于 Jackrabbit First Hops 示例,应选择哪个 Maven 原型(prototype)代码?

java - Java 中的非异常异常?

java - 使用 native 查询公开端点而不创建实体

database - JPA和2个简单的表

spring - persistence.xml - spring JPA

java - JPA/EclipseLink 未返回任何结果