简体   繁体   English

Hibernate JPA实体侦听器@Pre和@Post无法正常工作

[英]Hibernate JPA Entity listener @Pre and @Post don't work as expected

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: 这是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;
}

I'm using a separate API to insert/remove stars into DB. 我正在使用一个单独的API将星号插入/删除到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. 我确定它与Hibernate的缓存有关,但是我正在使用事务,并且所有事情都通过EntityManager所以我抓狂了。

From the documentation : 文档中

A callback method must not invoke EntityManager or Query methods! 回调方法不得调用EntityManagerQuery方法!

In practice, the behaviour if you do it is undefined, hence the results you observe in your examples. 实际上,行为是不确定的,因此您在示例中观察到的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM