我用过这个JPA: check whether an entity object has been persisted or not 要知道我是否坚持或合并我的实体,它将如下所示:
if (!getEntityManager().contains(entity)) {
System.out.println(" PERSIST ");
} else {
System.out.println(" MERGE ");
}
情况是 - 即使我编辑我的实体 - 它也不会被识别为合并。
这怎么可能以及如何让它发挥作用?
最佳答案
根据JPA 2.1 specification (PDF第72页),
EntityManager
方法public boolean contains(Object entity)
是:
Check if the instance is a managed entity instance belonging to the current persistence context.
因此,检查不是针对实际数据库进行的,而是针对当前 persistence context 进行的。 。
此外,在规范文档的 PDF 第 86 页上,我们发现:
The
contains
method returnstrue
:• If the entity has been retrieved from the database or has been returned by getReference, and has not been removed or detached.
• If the entity instance is new, and the persist method has been called on the entity or the persist operation has been cascaded to it.
The
contains
method returnsfalse
:• If the instance is detached.
很可能,在执行代码片段的调用代码时,您处于分离实体状态。因此,呼吁 contains(..)
始终评估为 false
.
作为替代方案,您可以使用
-
public <T> T find(Class<T> entityClass, Object primaryKey)
(参见第 66 页)或 -
public <T> T getReference(Class<T> entityClass, Object primaryKey)
(见第68页)
检查底层数据库中是否存在元组。您选择上述哪一种方法将取决于您的代码/应用程序的上下文。
希望有帮助。
关于java - 即使数据库中包含实体,为什么 'EntityManager.contains(..)' 也会返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113545/