Spring Data REST - Exception when PATCH is sent with an empty array in request body

岁酱吖の 提交于 2020-01-06 01:30:05

问题


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?


回答1:


You have to implements add/remove methods in the Atoll class.

So, your mapping :

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

And the two add/remove methods:

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

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


来源:https://stackoverflow.com/questions/48301383/spring-data-rest-exception-when-patch-is-sent-with-an-empty-array-in-request-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!