为什么即使数据库中包含实体,"EntityManager.contains(..)"也返回false? [英] Why does 'EntityManager.contains(..)' return false even if an entity is contained in DB?
问题描述
我使用了此 JPA:检查实体对象是否已保留 知道我是坚持还是合并实体,它看起来像这样:
I used this JPA: check whether an entity object has been persisted or not to know if i persist or merge my entity , It will look like this :
if (!getEntityManager().contains(entity)) {
System.out.println(" PERSIST ");
} else {
System.out.println(" MERGE ");
}
情况是-即使我编辑我的实体-也不会将其识别为合并.
The case is that - even if I edit my entity - it will not recognized as a merge.
这怎么可能以及如何使其起作用?
How is it possible and how to make it work?
推荐答案
According to the JPA 2.1 specification (PDF page 72),
EntityManager
方法public boolean contains(Object entity)
可以做到:
检查实例是否为属于当前持久性上下文的托管实体实例.
Check if the instance is a managed entity instance belonging to the current persistence context.
由于这个原因,不是针对实际数据库进行检查,而是针对当前 持久性上下文 .
For this reason, the check is not conducted against the actual database, but against the current persistence context.
此外,在规格文档的PDF第86页上,我们发现:
Moreover, on PDF page 86 of the spec document we find:
contains
方法返回true
:
•如果实体已从数据库中检索或由getReference返回,并且已未被删除或分离.
• If the entity has been retrieved from the database or has been returned by getReference, and has not been removed or detached.
•如果实体实例是新的,并且已在该实体上调用了persist方法,或者已将persisted操作级联到该实例.
• 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.
contains
方法返回false
:
•如果实例是分离的.
在执行代码片段的调用代码的那一刻,您很可能具有分离的实体状态.因此,对contains(..)
的调用始终评估为false
.
Most likely, you have a detached entity state in the moment the calling code of the code snippet is executed. Thus, the call for contains(..)
always evaluates to false
.
或者,您可以使用
-
public <T> T find(Class<T> entityClass, Object primaryKey)
(请参阅第66页)或 -
public <T> T getReference(Class<T> entityClass, Object primaryKey)
(请参阅第68页)
public <T> T find(Class<T> entityClass, Object primaryKey)
(see p. 66) orpublic <T> T getReference(Class<T> entityClass, Object primaryKey)
(see p. 68)
检查基础数据库中是否以元组的形式存在.您选择上述哪种方法取决于代码/应用程序的上下文.
to check the presence as a tuple in the underlying database. Which one of the above methods you chose will depend on the context of your code/application.
希望有帮助.
这篇关于为什么即使数据库中包含实体,"EntityManager.contains(..)"也返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!