jpa - OneToOne 关系上的 EclipseLink PreUpdate 未持久化

标签 jpa eclipselink entitylisteners

我有一个被执行的 PreUpdate 方法,但是在刷新 entityManager 时,依赖实体上的更改不会持久化。

以下是我的最小(非)工作示例:

实体

@Entity
@Table(name = "HOUSE")
public class House {

    @Id
    @Column(name = "ID")
    private long id;

    @OneToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "INFO_ID")
    private HouseInfo info;

    @PreUpdate
    protected void komplettiereEingabeWerte() {
        info.setCode("TEST");
    }

    //getters and setters
}

@Entity
@Table(name = "HOUSE_INFO")
public class HouseInfo {

    @Id
    @Column(name = "ID")
    private long id;

    @Column(name = "CODE")
    private String code;

    //getters and setters
}

测试用例
@Test
@Transactional(TransactionMode.ROLLBACK)
public void testPreUpdate() {
    House house = entityManager.find(House.class, 1L);
    house.setInfo(new HouseInfo());
    entityManager.flush();
    entityManager.clear();

    house = entityManager.find(House.class, 1L);
    assertEquals("TEST", house.getInfo().getCode());
}

由于代码为空,最后一行的 AssertionError 导致测试失败。

我将 EclipseLink 版本 2.7.4 与 Oracle DB 一起使用(使用内存中的 Derby DB 也观察到了相同的行为),并且测试正在 SpringApplicationContext 中使用 UnitilsJUnit4 运行。

我该如何解决这个问题?谢谢你。

最佳答案

JPA Spec指出:

In general, the lifecycle method of a portable application should not invoke EntityManager or query operations, access other entity instances, or modify relationships within the same persistence context. A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked



简单的答案是,实体监听器不能用于任务。而是在您的服务层中实现相关逻辑。

关于jpa - OneToOne 关系上的 EclipseLink PreUpdate 未持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289577/

相关文章:

jpa - 我可以在接口(interface)上注释@EntityListener 吗?

java - System.getproperty ("spring.profiles.active") 在 JPA 实体监听器中始终为 Null

java - JPA 多对多关联实体

java - 如何生成Hibernate字段注释?

java - Hibernate 的 NamedQueries 问题

java - 包含在 Set 上的 QueryDSL JPA 语法错误?

java - JPA持久性问题

hibernate - @GenerateValue(strategy = GenerationType.AUTO) 没有按预期工作

java - EclipseLink MOXy 具有相同类型的递归数据结构/子元素

用于命名查询删除操作的 hibernate 实体监听器