我正在尝试在Hibernate 3中实现一些事件监听器,它将在插入后事件上创建新实体。
以下是我最初尝试的代码:
@Override
public void onPostInsert(PostInsertEvent event) {
if (event.getEntity() instanceof MyEntity) {
final MyEntity myEntity = (MyEntity) event.getEntity();
final OriginalCopy originalCopy = new OriginalCopy(myEntity);
event.getSession().persist(originalCopy);
}
}
然而,通过检查日志,当我坚持一个新的MyEntity时,我希望看到类似的东西:
insert into original_entity values (...)
但实际做的是更新:
update original_entity set ... where original_entity_id = ...
所以我试着运气这个代码,现在它似乎正常工作:
@Override
public void onPostInsert(PostInsertEvent event) {
if (event.getEntity() instanceof MyEntity) {
final MyEntity myEntity = (MyEntity) event.getEntity();
final OriginalCopy originalCopy = new OriginalCopy(myEntity);
final SessionFactory sessionFactory = event.getSession().getSessionFactory();
final Session session = sessionFactory.openSession(event.getSession().connection());
final Transaction tx = session.beginTransaction();
session.persist(originalCopy);
tx.commit();
}
}
任何人都可以解释一下为什么我必须通过现有连接创建一个新会话才能看到它正常工作?