java - 了解 : "Cannot perform operation delete on detached object"

标签 java jpa entity openjpa

删除时出现以下实体抛出错误:

实体:

@Entity
@NamedQueries({
})
public class Server {
   //some attributes
}

我有以下非常简单的 JUnit 测试,它执行以下操作:

  1. 实体服务器已创建
    @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;
        }
    }
    
  2. 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/

相关文章:

java - WebElement.SendKeys(路径)问题 : org. openqa.selenium.InvalidArgumentException:参数无效:找不到文件

java - 将不同模式中的对象表映射到java数据类型

hibernate - 如何在 Spring Boot 上使用 Hibernate 生成自动 UUID

java - 当 JPA 实体不应准确反射(reflect)数据库上的物理模型时

html - &, &amp, & All 在 html 中的行为相似。如何以及为什么?

javascript - 看到 Aframe 实体

java - Drools 规则引擎验证服务 KnowledgeBuilder 初始化错误

java - 在 Java Swing 中销毁 JPopupMenu

java - 如何根据映射 URL 从 RestController 获取实体

java - 无法解析 org.apache.openjpa.persistence.PersistenceProviderImpl