Why does 'EntityManager.contains(..)' return false even if an entity is contained in DB?

戏子无情 提交于 2019-12-24 19:00:11

问题


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 returns true:

• 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 returns false:

• 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) or
  • public <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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!