【发布时间】:2017-02-21 12:53:07
【问题描述】:
我阅读了很多关于这方面的主题并进行了数百次实验,但到目前为止没有成功。我有以下课程:
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;
}
我所做的是尝试将children 列表替换为 PATCH 请求中提供的列表:
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。问题还在于您将所有内容都串联在一个循环中。从子对象的父字段中移除级联。 -
谢谢,看来我自己在同一时间发现了同样的问题 :)
标签: spring jpa spring-boot