我正在使用 Hibernate 3.5.6 尝试使用 Post-Insert 事件侦听器。我遇到了一种似乎与后处理事件的概念不一致的行为。我去向数据库提交一个对象,这会导致刷新会话并触发插入后事件。在触发后插入事件后,它会进行一些处理并最终抛出一个错误,然后一直返回到原始事务。正是在这里捕获了错误。我无法从此时回滚事务,并且数据库中没有条目。如果删除了插入后事件侦听器,我已经确认我的代码按预期执行。
休眠中的任何事后事件的预期行为是否会影响原始事务?我的理解是 post 事件应该完全独立于原始交易。
请参阅下面的代码段和堆栈跟踪。
堆栈跟踪
at ems.server.domain.IpeManager.getCrcMessage(IpeManager.java:113) ~[bin/:na]
at ems.shared.hibernateEvents.PostInsertListener.onPostInsert(PostInsertListener.java:34) [bin/:na]
at org.hibernate.action.EntityInsertAction.postInsert(EntityInsertAction.java:148) [hibernate3.jar:3.5.6-Final]
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:127) [hibernate3.jar:3.5.6-Final]
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267) [hibernate3.jar:3.5.6-Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259) [hibernate3.jar:3.5.6-Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178) [hibernate3.jar:3.5.6-Final]
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) [hibernate3.jar:3.5.6-Final]
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) [hibernate3.jar:3.5.6-Final]
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206) [hibernate3.jar:3.5.6-Final]
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375) [hibernate3.jar:3.5.6-Final]
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) [hibernate3.jar:3.5.6-Final]
at ems.server.database.dao.Dao.saveOrUpdate(Dao.java:30) [bin/:na]
at ems.server.database.dao.IpeComponentDao.insertComponent(IpeComponentDao.java:29) [bin/:na]
at ems.server.domain.NetworkManager.insertIpeConfig(NetworkManager.java:2876) [bin/:na]
道类
Session session = HibernateUtil.currentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
return obj;
} catch (ConstraintViolationException e) {
if (tx != null)
tx.rollback();
throw e;
} catch (HibernateException he) {
if (tx != null)
tx.rollback();
throw new HibernateException("Could not save object of class " + obj.getClass().getName(), he);
}
休眠.cfg.xml
<event type="post-insert">
<listener class="ems.shared.hibernateEvents.PostInsertListener"/>
</event>
PostInsertListener 类
package ems.shared.hibernateEvents;
import java.util.*;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
public class PostInsertListener implements PostInsertEventListener{
private static final long serialVersionUID = 2L;
public void onPostInsert(PostInsertEvent event) {
//DO SOME PROCESSING HERE
}
}