Pio*_*cki 43
要检查给定实体是否由当前实体管理,PersistenceContext您可以使用EntityManager#contains(Object entity).
Ste*_*ers 14
Piotr Nowicki的答案提供了一种确定实体是否被管理的方法.为了确定实体是否已被分离,我们需要知道它是否先前已被管理(即来自数据库,例如通过持久化或从find操作获得).Hibernate没有提供"实体状态历史记录",因此简短的回答是没有100%可靠的方法,但在大多数情况下,以下解决方法应该足够了:
public boolean isDetached(Entity entity) {
return entity.id != null // must not be transient
&& !em.contains(entity) // must not be managed now
&& em.find(Entity.class, entity.id) != null; // must not have been removed
}
Run Code Online (Sandbox Code Playgroud)
以上假设em是EntityManager,Entity是实体类,并且具有id作为@GeneratedValue主键的公共字段.(它还假定在分离实体后,外部进程没有从数据库表中删除具有此ID的行.)