Cascade on Many To Many

The many to many relationship is complex because both sides of this association have roles of parent and child. Moreover, only one side can be identified from where we’d like to propagate the state changes of the entity.

We shouldn’t default to CascadeType.ALL, because the CascadeTpe.REMOVE could delete more than we’re expecting (as you’ll soon find out):

@Entity
public class Author {
...
@ManyToMany(mappedBy = "authors",
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Book> books = new ArrayList<>();
...
}
@Entity
public class Book {
...
@ManyToMany(cascade =
{CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "Book_Author",
joinColumns = {
@JoinColumn(
name = "book_id",
referencedColumnName = "id"
)
},
inverseJoinColumns = {
@JoinColumn(
name = "author_id",
referencedColumnName = "id"
)
}
)
private List<Author> authors = new ArrayList<>();
...
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.109.141