【问题标题】:Spring, JPA - bidirectional @OneToMany: replace child list with anotherSpring,JPA - 双向@OneToMany:用另一个替换子列表
【发布时间】: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


【解决方案1】:

找到解决方案。

我应该有 orphanRemoval=true:

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval=true)

现在它删除了父级,因为 @ManyToOne 中的另一个级联。我将其更改为以下内容:

@ManyToOne(cascade = {CascadeType.MERGE})

现在可以了。

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多