1

我正在尝试在 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();

    }

}

谁能解释我为什么必须在现有连接上创建一个新会话才能看到它工作?

4

0 回答 0