Search code examples
jspspring-mvcmany-to-manyhibernate-mappingdao

Remove one element removes the binding of other elements Many to Many Hibernate


There are two tables: authors and books. Communication between Many to Many.

Author

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "authorList",cascade= {CascadeType.PERSIST} )
private List<Book> bookList; 

Book

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name= "author_book",
           joinColumns = {@JoinColumn(name="book_id",nullable=false)},
           inverseJoinColumns = {@JoinColumn(name="author_id",nullable = false)})
private List<Author> authorList; 

Table

Book1(Author1)

Book2(Author1, Author2)

In this embodiment, if the author delete the table takes the form

Book1()

Book2(Author2)

if I type in the class authors cascade Cascade.ALL, it removes all of the books in which this author is mentioned

Question: What should I do to when removing the author, and have removed all of his books, but if the book has multiple authors, it was removed to only the value of the author in this book.


Solution

  • I think you should not rely on cascade (you can read that question here: many-to-many cascade delete) for that case, and delete the entities by yourself (eg: create a service that remove an author and delete all books only owned by him).

    You could also try to represent the many to many by one intermediate entity, like BookAuthor, and have something like :

    Book <--> BookAuthor <--> Author

    • Book has a list of "BookAuthor" (ManyToOne)
    • Author has a list of "BookAuthor" (ManyToOne)

    That way, deleting an author (with cascade = delete) would destroy the BookAuthor link, but leave the Book even if there are no remaining author of it.