删除时出现以下实体抛出错误:
实体:
@Entity
@NamedQueries({
})
public class Server {
//some attributes
}
我有以下非常简单的 JUnit 测试,它执行以下操作:
- 实体服务器已创建
@Transactional public class ServerDao { public Server update(Server entity, long userId) { entity.setDeleted(false); if (entity.getId() > 0) { if (userId > 0) { entity.setUpdated(new Date()); entity.setUpdatedby(usersDao.get(userId)); } em.merge(entity); } else { if (userId > 0) { entity.setInserted(new Date()); entity.setInsertedby(usersDao.get(userId)); } em.persist(entity); } return entity; } }
Entity Server is deleted
... same Dao
public void deleteHardJUnit(Server entity) { em.remove(entity); }
This will throw an exception like:
org.apache.openjpa.persistence.ArgumentException: You cannot perform operation delete on detached object "org.apache.openmeetings.persistence.beans.basic.Server-1".
If I change the delete method to:
public void deleteHardJUnit(Server entity) {
if (entity.getId() > 0) {
em.refresh(entity);
em.remove(entity);
}
}
一切“似乎”都按预期工作,没有抛出异常,并且记录已从数据库中删除。
但是我不确定这意味着什么,我们真的需要在删除每个实体之前刷新它吗?因为我之前已经多次使用 EntityManager.delete 而无需刷新实体。
最佳答案
假设您使用 Spring 的 @Transactional
注释,它无法拦截来自注释对象实例内的调用(由于 Spring 使用动态代理进行 AOP 和方法拦截)。尝试从服务层调用并注释那里的方法。
如果您不使用 Spring,那么您可能希望使用 @TransactionAttribute
,这是类似的 Java EE 注释。
关于java - 了解 : "Cannot perform operation delete on detached object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658158/