我有一个被执行的 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/