查看任意对象是否为 JPA 实体的正确方法是什么?



javax.persistence.EntityManager#contains(Object)方法的文档说(部分):

检查实例是否是属于当前持久性上下文的托管实体实例。抛出:IllegalArgumentException- 如果不是实体

JPA 2.1 规范的第 3.1.1 节说:

如果持久性上下文已加入当前事务,则EntityManager接口的方法(contains(Object)例如IllegalArgumentException](如LockTimeoutException)引发的运行时异常(如)将导致当前事务被标记为回滚。

那么,在不回滚当前事务的情况下检查任意对象(不知道它是否是实体,不知道它是否在持久性上下文中)是否既是实体又在持久性上下文中的首选方法是什么?

您可以在新事务中检查它,这不会影响您当前的事务。


一些注意事项这是您上一个问题的一个很好的例子,当时我回答说规范的某些部分没有正确制定。我给你举一个例子,它没有任何问题,这与规范相矛盾(至少在带有 Hibernate 的 JBoss 7.1 中):

public class EjbServiceBean implement EjbService {
@PersistenceContext
private EntityManager em;
@Override
public void testTransaction() {
//this code is in a transaction EJB method
MyEntity entity = em.find(MyEntity.class, 1L);
entity.setPeristentField("New Value");
try {
em.find(Class.class, 1);//should rollback the transaction
} catch (Exception e) {
//simply catching the Exception, so that the CMT transaction is not rolled back by the EJB container.
}
//but after the method returns, the entity instance is commited.
}
}

在这个例子中,我的意思是你可以在实践中使用em.contains()方法来检查一个类是否是实体类。

PS:这也在 2.0 规范中指定。

相关内容

最新更新