【发布时间】: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方法中使用的createdDate是Auditable 类的一部分)。
那么是什么导致了这个异常,我该如何解决呢?
【问题讨论】:
-
你解决了这个问题吗?
-
ans中的方法不起作用
-
为什么使用 createdDate 来表示 hashcode 和 equals?为什么没有身份证?你可以尝试改变它,看看你是否得到相同的结果?或者也许两者都用。我想知道是否可能是两个这样的对象具有相同的 createdDate,这可能会产生冲突。
-
你也可以试试这个cristian.sulea.net/…
标签: java spring hibernate spring-boot spring-data-rest