【问题标题】:App Engine JPA 2 get error message when deleting an entity "trying to remove detached instance but operation requires it to be attached"App Engine JPA 2 删除实体时收到错误消息“尝试删除分离的实例,但操作需要附加它”
【发布时间】:2014-07-09 09:25:08
【问题描述】:

我有一个使用 JPA 2 存储数据的 Java App Engine 应用。当我尝试删除实体时,我收到错误消息:

"...试图删除分离的实例,但操作要求它是 附上”

/**
 * Delete the customer
 */
protected void deleteCustomer(long id){
    EntityManager em = EMF.get().createEntityManager();

    try{
        Customer customer = getCustomerById(id);
        em.remove(customer);
    }
    finally{
        em.close();
    }
}

/**
 * Utility funciton used to retrieve customers
 */
protected Customer getCustomerById(long id){

    EntityManager em = EMF.get().createEntityManager();

    try{
        Key key = KeyFactory.createKey(Customer.class.getSimpleName(), id);
        return em.find(Customer.class, key);
    }
    finally{
        em.close();
    }

}

【问题讨论】:

    标签: java google-app-engine jpa


    【解决方案1】:

    您需要使用相同的 EntityManager 类进行查找和删除。通过将 EntityManager 作为原始 a 参数传递给删除函数来解决该问题,例如(更新问题中的代码):

    /**
     * Delete the customer
     */
    protected void deleteCustomer(long id){
        EntityManager em = EMF.get().createEntityManager();
    
        try{
            Customer customer = getCustomerById(em, id);
            em.remove(customer);
        }
        finally{
            em.close();
        }
    }
    
    /**
     * Utility funciton used to retrieve a customer by id
     */
    protected Customer getCustomerById(EntityManager em, long id){
    
        Key key = KeyFactory.createKey(Customer.class.getSimpleName(), id);
        return em.find(Customer.class, key);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多