【问题标题】:Spring Data REST - Exception when PATCH is sent with an empty array in request bodySpring Data REST - 在请求正文中使用空数组发送 PATCH 时出现异常
【发布时间】:2018-06-26 08:24:21
【问题描述】:

我正在使用 Spring Data REST,并且我的域中有以下实体。

Atoll.class

@Entity
@Data
public class Atoll {

    @Id
    @GeneratedValue
    private Long id;

    private String atollName;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "atoll_id")
    private List<Island> islands = new ArrayList<>();

}

Island.class

@Entity
@Getter
@Setter
public class Island extends Auditable{

    @Id
    @GeneratedValue
    private Long id;

    private String islandName;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Island that = (Island) o;
        return Objects.equals(this.getCreatedDate(), that.getCreatedDate());

    }

    @Override
    public int hashCode() {
        return Objects.hash(this.getCreatedDate());
    }

}

现在我可以通过使用以下 JSON 向 /atolls 端点发送 POST 来保留 Atoll 和 Islands。

{
    "atollName":"Haa Alif",
    "islands":[{
        "islandName":"Dhidhdhoo"
    }]
}

但是当我向 atolls/1 发送一个带有空岛数组的 PATCH 以删除环礁中的所有岛屿时,它给了我以下异常

A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: com.boot.demo.model.Atoll.islands; nested exception is org.hibernate.HibernateException: A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: com.boot.demo.model.Atoll.island

我搜索了stackoverflow并找到了这个answer,它说这主要是由于equals和hashCode方法引起的,所以我覆盖了默认的equals和hashCode方法,但错误仍然相同(equals方法中使用的createdDateAuditable 类的一部分)。

那么是什么导致了这个异常,我该如何解决呢?

【问题讨论】:

  • 你解决了这个问题吗?
  • ans中的方法不起作用
  • 为什么使用 createdDate 来表示 hashcode 和 equals?为什么没有身份证?你可以尝试改变它,看看你是否得到相同的结果?或者也许两者都用。我想知道是否可能是两个这样的对象具有相同的 createdDate,这可能会产生冲突。
  • 你也可以试试这个cristian.sulea.net/…

标签: java spring hibernate spring-boot spring-data-rest


【解决方案1】:

您必须在 Atoll 类中实现添加/删除方法。

所以,你的映射:

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "atoll_id")
private List<Island> islands = new ArrayList<>();

还有两个添加/删除方法:

public void addIsland(Island island) {
    this.getIslands().add(island);
}

public void removeIsland (Island island) {
    this.getIslands().remove(island);
}

【讨论】:

  • 如果我添加这些方法,spring data REST 会自动处理它们吗?
  • 我想是的,是的。父实体具有这两种方法,用于同步 @OneToMany 关联。看看这篇文章:vladmihalcea.com/…
  • 我还没试过。但我会告诉你我是否可以让它工作
猜你喜欢
  • 2015-03-07
  • 1970-01-01
  • 2016-07-18
  • 2017-11-24
  • 2019-07-06
  • 2016-03-23
  • 2023-01-11
  • 1970-01-01
  • 2011-07-15
相关资源
最近更新 更多