I have a problem with my code in @Manytomany hibernate relationship.
I see above issue is due to "CascadeType.ALL" on @ManyToMany relationship side. But if i remove this CascadeType.ALL in @ManyToMany. If I change this CascadeType.ALL in @ManyToMany with CascadeType.PERSIST and CascadeType.MERGE, I solve the problem. But when I add new an object will get an error. otherwise, if I change it to CascadeType.ALL, when adding new objects it works fine but it doesn't solve the problem I'm discussing. So how can I keep the rows in the Class Tag when deleting rows in Post.
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
public Post() {}
public Post(String title) {
this.title = title;
}
@ManyToMany(cascade = {
CascadeType.ALL
},fetch = FetchType.EAGER)
@JoinTable(name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
}
//
public class Tag {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String nameTag;
@ManyToMany(mappedBy = "tags",fetch = FetchType.LAZY)
private List<Post> posts = new ArrayList<>();
public Tag() {}
public Tag(String nameTag) {
this.nameTag = nameTag;
}
}
As I said above if it is CascadeType.ALL I will not be able to retain the row in Tag when I delete a row in Post when I write it is CascadeType.PERSIST and CascadeType.MERGE i get an error: object references an unsaved transient instance - save the transient instance before flushing.
And this is my input API object:
{
"title": "System",
"tags": [
{
"nameTag": "apt"
},
{
"nameTag":"Worm"
}
]
}
Remember that the api input works fine when I use Casecade.ALL