Answer the question
In order to leave comments, you need to log in
How is the relationship removed in Hibernate in this case?
How is deletion done in Hibernate in this example?
@Test
@DisplayName("отсоединение книги от автора")
public void whenDeleteAuthorFromBook_thenOneDeleteStatement() {
Author author = authorRepository.findByName("a1");
Book book = bookRepository.findByName("b1");
author.removeBook(book);
}
@NoArgsConstructor
@Data
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
public Author(String name){
this.name=name;
}
@ManyToMany (cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "author_book",
joinColumns = @JoinColumn(name = "author_id"),
inverseJoinColumns = @JoinColumn(name = "book_id")
)
private List<Book> books=new ArrayList<>();
public void addBook(Book book){
this.books.add(book);
book.getAuthors().add(this);
}
public void removeBook(Book book){
this.books.remove(book);
book.getAuthors().remove(this);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Author)) return false;
return id != null && id.equals(((Author) o).getId());
}
@Override
public int hashCode() {
return 31;
}
}
@NoArgsConstructor
@Data
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
@ManyToMany(mappedBy = "books")
private Set<Author> authors=new HashSet<>();
public Book(String name){
this.name=name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Author)) return false;
return id != null && id.equals(((Book) o).getId());
}
@Override
public int hashCode() {
return 31;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question