【发布时间】:2016-01-20 10:22:18
【问题描述】:
在我的数据库中保存实体时遇到问题。
我有类似的东西(非常简化):
@Entity
public class Building {
@OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
private List<Employee> employees;
}
@Entity
public class Employee {
@NotNull
@ManyToOne
@JoinFetch(INNER)
@JoinColumn
private Building building;
@PostLoad
private void onLoad(){
if (this.plannedOrder == null) {
//For old entities in this DB, update plannedOrder if null
if (this.order < FIRST.getCode()) {
this.plannedOrder = FIRST;
} else if (this.order >= FIRST.getCode() && this.order < SECOND.getCode()) {
this.plannedOrder = SECOND;
} else if (this.order >= DEFAULT.getCode() && this.order < SEC_LAST.getCode()) {
this.plannedOrder = DEFAULT;
} else if (this.order >= SEC_LAST.getCode() && this.order < LAST.getCode()) {
this.plannedOrder = SEC_LAST;
} else if (this.order >= LAST.getCode()) {
this.plannedOrder = LAST;
} else {
this.plannedOrder = DEFAULT;
}
}
}
问题是当我保存一个 Employee 实体时。在 Building 实体中,您将修改所有员工,因为 @PostLoad 注释,因此 JPA 将尝试更新这些实体。但是,我只想更新 Employee 实体。
有什么方法可以在不改变模型关系的情况下做到这一点吗?是否可以作为移除 onLoad 功能的解决方案?
谢谢!
已编辑:
添加了 PostLoad 的 PostLoad 代码。这是对 DB 中的旧实体执行的修复,在保存时没有更新此字段。
已编辑 2
这就是我使用 EntityManager 保存实体 Employee 的方式(如果是新对象,则保留,否则更新它)
if (entity.getId() == null) {
entityManager.persist(entity);
return entity;
}
return entityManager.merge(entity);
【问题讨论】:
-
你没有在这里定义任何级联。显示@PostLoad的代码..
-
您提供的代码中没有任何内容可以将
Employee的一个更新级联到Building或Building的另一个Employees。显示你“保存”了Employee。 -
是的,我同意你的看法。我添加了如何保存此实体。
-
会不会是你在一个事务中也修改了另一个
Employees?请记住,事务中检索到的对象的任何更改都将被持久化,而无需调用merge-方法。另外,当你说员工被“修改”时,这是什么意思? -
当我说员工实体被修改时,我的意思是从我的员工实体中检索建筑物时 PostLoad 方法所做的更改。我不认为我正在更改 Transaction 中的任何 Employee,只是 PostLoad,但我会仔细研究一下。
标签: java jpa eclipselink cascade many-to-one