How to identify an object is transient or detached in hibernate?

前端 未结 5 786
無奈伤痛
無奈伤痛 2021-01-01 16:04

I know that transient instance means the instance is newly created and its corresponding row does not exist in the database where as detached instance has corresponding entr

5条回答
  •  粉色の甜心
    2021-01-01 16:46

    In order to check if object e is in :-

    1. Persistence Context :- EntityManager.contains(e) should return true.

    2. Detached State : PersistenceUnitUtil.getIdentifier(e) returns the value of the entity’s identifier property.

    3. Transient State :- PersistenceUnitUtil.getIdentifier(e) returns null

    You can get to the PersistenceUnitUtil from the EntityManagerFactory.

    There are two issues to look out for. First, be aware that the identifier value may not be assigned and available until the persistence context is flushed. Second, Hibernate (unlike some other JPA providers) never returns null from Persistence- UnitUtil#getIdentifier() if your identifier property is a primitive (a long and not a Long).

提交回复
热议问题