我正在使用Hibernate Interceptor(hibernate 4.x)。我想对Session的save方法执行一些操作。所以我扩展了EmptyInterceptor。
它有以下方法:
onSave() //when save operation is preformed.
postFlush() //called after committed into database
问题:在postFlush()中我想执行SAVE操作。所以我的控制陷入了循环。因为当调用session.save()时,调用EmptyInterceptor的onSave()和postFlush()方法来拦截SAVE操作。
要删除此问题,我使用了两个会话工厂。 1用于执行会话操作(保存,更新等),第二个用于HibernateIntercepter。
但我担心如何使用单个sessionFactory来解决这个问题?
公共类AudiLogInterceptor扩展了EmptyInterceptor {
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
return false;
}
// called after committed into database
public void postFlush(Iterator iterator) {
// want to perform SAVE operation here with Session.save()
// But whenever I open new seesion here. It falls in loop
Session tempSession = HibernateUtil.hibernateTemplateLog
.getSessionFactory().openSession();
try {
Item item = new Item();
item.setName("anyItem");
item.setValue("anyValue");
tempSession.save(item);
tempSession.flush();
} finally {
tempSession.close();
}
}
}
答案 0 :(得分:0)
您不使用拦截器来保存对象。您可以使用它来修改/格式化项目,让会话对象为您完成剩下的工作但不添加新项目。
如果你真的想在flush()或commit()的末尾添加一行,那么你可以使用Spring-AOP作为一个选项。在那里你可以添加对hibernate服务的Advises,因此,你可以在运行方法后立即保存。
解决方法我认为如下。
public void postFlush(Iterator iterator) {
for(; iterator.hasNext();) {
if(!(iterator.next() instanceof Item)){ //<<<<< You verify if you are saving Item or //other objects, if saving Item, skip this block.
Session tempSession = HibernateUtil.hibernateTemplateLog
.getSessionFactory().openSession();
try {
Item item = new Item();
item.setName("anyItem");
item.setValue("anyValue");
tempSession.save(item);
tempSession.flush();
} finally {
tempSession.close();
}
}
}
}
}