【发布时间】:2011-01-05 14:57:30
【问题描述】:
您知道任何了解 JPA 实体状态的方法吗?我遇到了一些错误,我需要知道实体是分离的还是托管的。
我正在使用 EclipseLink 2.1.2
【问题讨论】:
标签: jpa eclipselink
您知道任何了解 JPA 实体状态的方法吗?我遇到了一些错误,我需要知道实体是分离的还是托管的。
我正在使用 EclipseLink 2.1.2
【问题讨论】:
标签: jpa eclipselink
检查实例是否是属于当前持久性上下文的托管实体实例。
【讨论】:
前面的答案部分正确。
您必须检查其他州以获得更高的置信度。
我使用以下代码,其中我有自己的托管 EntityManager / EntityManagerFactory。
/**
* Check if an entity is detached or not
* @param entity
* @return true, if the entity is managed
*/
public boolean isDetached(AbstractEntity entity) {
// pick the correct EntityManager, somehow
EntityManager em = getMyEntityManager(entity);
try {
if (em == null)
return false;
return entity.getID() != null // must not be transient
&& !em.contains(entity) // must not be managed now
&& em.find(Entity.class, entity.getID()) != null; // must not have been removed
} finally {
if (em != null)
em.close();
}
}
【讨论】: