2

I have two POJOs, one is for Post which is below

@Entity
public class Post {
    ...
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "category_id")
    private Category category;
    ...
}

and another one is for Category as below

@Entity(name = "category")
public class Category {
    ...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<Post> post;
    ...
}

I have two crud repositories for each class. And here is my issue. GET, POST, PUT is working as expected. But for DELETE it is creating the issue. Suppose POST A has Category type C. When I am trying to delete POST A it is not only deleting POST A itself also deleting Category C and all Posts related to Category C.

Please help :)

  • Please be more careful when using annotations or code that you have seen somewhere in general. Make sure that you first understand what you use. This question might help you: https://stackoverflow.com/questions/13027214/what-is-the-meaning-of-the-cascadetype-all-for-a-manytoone-jpa-association – Eirini Graonidou Jul 18 '20 at 13:33
  • Thank you @EiriniGraonidou. will keep this in mind. The link you shared is really helpful :) – Sayantan Banerjee Jul 18 '20 at 13:45

1 Answers1

3

The problem is in the CascadeType, of the Post side. CascadeType.ALL includes CascadeType.REMOVE, so when you delete a post, the category to which that post belongs will be removed as well. Retain only CascadeType.ALL on the Category side and remove it from Post.

jwpol
  • 1,188
  • 10
  • 22