I am using Spring Data REST and I have the following entities in my domain.
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());
}
}
Now I can persist both Atoll and Islands by sending a POST to /atolls endpoint with the following JSON.
{
"atollName":"Haa Alif",
"islands":[{
"islandName":"Dhidhdhoo"
}]
}
But when I send a PATCH to atolls/1
with an empty array of islands to remove all the islands in the atoll it gives me the following exception
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
I searched stackoverflow and found this answer where it says this mainly occurs due to equals and hashCode method so I override the default equals and hashCode method but the error is still the same(the createdDate
used in equals method is part of Auditable
class).
So what causes this exception and how do I fix this?