簡體   English   中英

為什么JPA可以保存我的實體但不能刪除該實體?

[英]why JPA can save my entity but It can't delete the entity?

在我的JSF2-JPA2-Spring3項目中,我可以插入新實體,但不能刪除實體。 這是錯誤消息:java.lang.IllegalArgumentException:刪除分離的實例實體。Entity#8

這是我的persistence.xml:

<?xml version="1.0" encoding="UTF-8" ?>

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd“ version =” 1.0“>

<persistence-unit name="myPersistenceUnit"
    transaction-type="RESOURCE_LOCAL">
    <properties>            
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="hibernate.show_sql" value="true" />
    </properties>   
</persistence-unit>

這是我的服務:

@Service("myService")

公共類MyServiceImpl實現MyService {

@Resource(name="MyRepository")
MyDAO myDao;

@Transactional
public void deleteEntity(Entity entity) throws DAOException {
    myDao.delete(entity);
}

這是我的道:

@Repository("MyRepository")

公共類UserDAO {

private EntityManager entityManager;

@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
}

public void delete(Entity entity) throws Exception {

    try {
        entityManager.remove(entity);
    } catch (DataAccessException e) {
        throw new Exception(e);
    }
}

這是applicationContext.xml:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >

        </bean>
    </property>
    <property name="dataSource" ref="myDataSource" />
    <property name="persistenceUnitName" value="myPersistenceUnit"/> 
</bean>

<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />     
</bean>

<tx:annotation-driven />
<tx:annotation-driven  transaction-manager="transactionManager"/>


<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" rollback-for="Throwable" />
    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:advisor pointcut=" execution(* service.*Service.*(..))"
        advice-ref="transactionInterceptor" />
</aop:config>

我嘗試從使用dao中的此方法提供的列表中刪除實體:

public List<Entity> getAll() throws Exception {
    List<Entity> list = null;

    try {
          list = entityManager.createQuery("Select e from Entity e").getResultList();
    } catch (DataAccessException e) {
        throw new Exception(e);
    }

    return list;
}

該錯誤告訴您要刪除的實體無法刪除,因為它與當前的持久性上下文無關。 如果您在一個事務中讀取該實體,然后在另一個事務中嘗試刪除(或更新它),則可能會發生這種情況,因為持久性上下文的作用域是該事務。

要修復它,請更改您的DAO,首先將實體合並回持久性上下文中,然后將其刪除:

Entity newEntity = entityManager.merge(entity);
entityManager.remove(newEntity);

注意:EntityManager.merge()返回一個實體,該實體是當前持久性上下文的一部分-您傳遞的實體仍然是分離的。

另外,您可以刪除帶有JPQL的實體:

public void delete(Entity entity) {
    em.createQuery("DELETE FROM Entity e WHERE e.id = :id")
            .setParameter("id", entity.getId())
            .executeUpdate();
}

另一種方法可以是:

Entity newEntity = entityManager.getReference(Entity.class, entity.getId());
entityManager.remove(newEntity);

通用DAO實現周圍有一些教程:

public void delete(T entity) {
    entityManager.remove(entity);
}

我得到了相同的刪除分離的實例實體錯誤 ,所以我將其更改為:

public void delete(T entity) {
    T eT = entityManager.merge(entity);
    entityManager.remove(eT);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM