问题
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?
回答1:
According to the JPA 2.1 specification (PDF page 72),
the EntityManager
method public boolean contains(Object entity)
does:
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.
Moreover, on PDF page 86 of the spec document we find:
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.
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
.
As an alternative, you can use
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.
Hope it helps.
来源:https://stackoverflow.com/questions/49113545/why-does-entitymanager-contains-return-false-even-if-an-entity-is-containe