0
我读了很多的主题,并做了数百个实验,但迄今尚未成功。我有以下类:Spring,JPA - 双向@OneToMany:用另一个替换子列表
class Parent {
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL/*, orphanRemoval=true*/)
private List<Child> children = new ArrayList<>();
class Child {
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "parentId", nullable = false)
@JsonIgnore
Parent parent;
}
我所做的就是尽量在PATCH请求中提供的一个替换children
列表:
Hibernate.initialize(fromDb.getChildren());
entityManager.detach(fromDb); // detach from JPA. I need this
List<Child> newChildren = fromClient.getChildren();
fromDb.getChildren().clear(); // get rid of all old elements
for (Child child : newChildren) { // add the new ones
child.setParent(fromDb);
fromDb.getChildren().add(child);
}
ParentRepository.save(merged);
行为是以下几点:
- 当我运行它因为它是,它增加了新的,但离开旧的 !所以我越来越多的多余的孩子(对不起..)
- 当我 取消注释
orphanRemoval=true
部分... 父母被删除!
你能解释为什么它的行为如此吗?我能在这里做什么?
因为这就是你配置它做的事情......你删除了'orphanRemoval = true'。问题在于你在循环中将所有东西级联起来。从子对象的父字段中删除级联。 –
谢谢,看起来像我在同一时间自己找到同样的问题:) – kiedysktos