Hibernate JPA Entity侦听器@Pre和@Post无法按预期工作 [英] Hibernate JPA Entity listener @Pre and @Post don't work as expected

查看:110
本文介绍了Hibernate JPA Entity侦听器@Pre和@Post无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个实时应用程序,并尝试使用实体监听器来保持我的状态为最新状态。基本思想是,无论何时某个业务逻辑领域发生变化,我都会重新加载受影响的实体并协调这些变更。这是一个MWE:

I'm building a real time app and trying to use entity listeners to keep my state up to date. The basic idea is that whenever an area of business logic changes, I re-load the affected entities and reconcile the changes. Here's a MWE:

@PrePersist
public void PrePersist() {
    LoggerFactory.logger(App.class).info(" >>> PrePersist count: " + getStars().size());
}
@PostPersist
public void PostPersist() {
    LoggerFactory.logger(App.class).info(" >>> PostPersist count: " + getStars().size());
}
@PreRemove
public void PreRemove() {
    LoggerFactory.logger(App.class).info(" >>> PreRemove count: " + getStars().size());
}

@PostRemove
public void PostRemove() {
    LoggerFactory.logger(App.class).info(" >>> PostRemove count: " + getStars().size());
}
private List<Star> getStars() {
    EntityManager em = HibernateUtilJpa.getEntityManager();
    List<Star> l = new ArrayList<Star>();
    try {
        em.getTransaction().begin();
        l = em.createQuery("from Star", Star.class).getResultList();
        em.getTransaction().commit();
    } catch (Exception e) {
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
    return l;
}

我正在使用一个单独的API向数据库中插入/删除星星。我期待后继者会因为添加的项目而显示更多项目,并且删除后的项目数量会少于预先移除的项目数量。事实并非如此,后续持久化和移除后都显示不正确的项目数,因此预留持久性与持久性持久性相同,并且预先移除与移除后相同。我确信它与Hibernate-s缓存有关,但我使用的是事务,一切都通过 EntityManager ,所以我在挠头。

I'm using a separate API to insert/remove stars into DB. I was expecting that post-persist would show one item more because of the added item, and post-remove would be one fewer than pre-remove. This is not the case, both post-persist and post-remove show the incorrect number of items, so pre-persist is the same as post-persist, and pre-remove is the same as post-remove. I'm sure it has to do with Hibernate-s caching, but I'm using transactions and everything goes through the EntityManager so I'm scratching my head.

推荐答案

documentation
$ b

From the documentation:


回调方法不能调用 EntityManager Query methods!

A callback method must not invoke EntityManager or Query methods!

在实践中,如果你这样做的行为是未定义的,那么你在例子中观察到的结果。

In practice, the behaviour if you do it is undefined, hence the results you observe in your examples.

这篇关于Hibernate JPA Entity侦听器@Pre和@Post无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆