根据 JB Nizet 的回答,我将我的 DAO 更改为具有 DeleteOperationListener(我的基本 DAO 实现基于“不要重复 DAO”[1]。)这样我就有了一个通用的解决方案,以防我发现自己处于相同的状态又是情况。结构如下所示:
public interface GenericDao<T, PK extends Serializable> {
// CRUD methods
// delete operation listeners.
void addDeleteListener(DeleteOperationListener<T, PK> deleteOperationListener);
public interface DeleteOperationListener<T> {
void preDelete(T entity);
void posDelete(T entity);
}
}
我的抽象休眠实现可以通知观察者删除。
@Override
public void delete(T entityToDelete) {
notifyPreDelete(entityToDelete);
this.getHibernateTemplate().delete(entityToDelete);
notifyPosDelete(entityToDelete);
}
现在我有一个不同的类来处理子项的删除,而无需更改 DAO:
@Service
public class ParentModificationListener
implements GenericDao.DeleteOperationListener<Parent> {
private ChildDao childDao;
@Autowired
public ParentModificationListener(ChildDao childDao, ParentDao parentDao) {
this.childDao = childDao;
parentDao.addDeleteListener(this);
}
@Override
public void preDelete(Parent parent) {
this.childDao.deleteChildrenFromParent(parent);
}
@Override
public void posDelete(Parent parent) {
// DO NOTHING
}
}
[1] http://www.ibm.com/developerworks/java/library/j-genericdao.html