2013-03-29 35 views
0

我想覆盖某些实体的EntityManager.remove()方法,以便我可以将active布尔值属性设置为false,而不是完全从数据库中删除对象。这可以被看作是一个软删除。覆盖Spring Roo中的EntityManager.remove()

Entity_Roo_Jpa_ActiveRecord.aj文件为我的类(称为Entity,作为超)remove方法是这样的:

@Transactional 
public void remove() { 
    if (this.entityManager == null) this.entityManager = entityManager(); 
    if (this.entityManager.contains(this)) { 
     this.entityManager.remove(this); 
    } else { 
     Entity attached = Entity.findEntity(this.id); 
     this.entityManager.remove(attached); 
    } 
} 

我发现其中的EntityManagerFactoryMETA-INF/spring/applicationContext.xml使用的定义:

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> 
    <property name="entityManagerFactory" ref="entityManagerFactory"/> 
</bean> 
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/> 
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> 
    <property name="persistenceUnitName" value="persistenceUnit"/> 
    <property name="dataSource" ref="dataSource"/> 
</bean> 

是否可以子类LocalContainerEntityManagerFactoryBean并提供我自己的EntityManager为某一类,或者有更好的方法吗?

我也注意到使用@PersistenceContext派发EntityManager的一个属性:

@PersistenceContext 
transient EntityManager Entity.entityManager; 

但我怀疑这只是存储EntityManager对象,而不是指定要使用的实现类(自EntityManager是一个接口)。

编辑:答案可能在于this answer

回答

2

有几种方法可以做到这一点。

1.推入式重构remove()方法

而不是去所有的方式来改变的EntityManager的,你可以在remove()方法推入重构你的实体类,并设置active值为方法内的false,并致电merge()

另请注意,您需要修改取景器和大多数其他方法来过滤设置为active=false的实体。

2. Spring Roo的行为附加@RooSoftDelete注释

您也可以使用下面的Spring Roo附加组件使软删除。

https://redmine.finalconcept.com.au/projects/final-concept-spring-roo-behaviours/wiki/Soft-delete-annoation

它可以让你添加一个名为@RooSoftDelete新的注释这需要软删除的照顾。

除了上述内容外,您还可以编写一个自定义实体管理器工厂,该工厂将负责处理所有问题。

干杯。

+0

感谢您的第一个方法,我已经通过将Entity.remove()方法从方面移动到了我的Entity类中来完成此操作,但这不会级联remove()(因为我我不再使用我推测的实体经理)。 –