B
B
Biaci_Anj2021-07-17 22:11:27
Hibernate
Biaci_Anj, 2021-07-17 22:11:27

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);
    }

I thought we should go to the repository to remove something. And here we just removed the object from the collection, which has the ManyToMany annotation.
Or will Hibernate remember and the deletion will happen the next time I call DB from the repository? If so, how is this consistent with other methods that work by getting data from the DB, won't they get the data from the remote book?

Entity Author
@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;
    }
}

Entity Book
@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 question

Ask a Question

731 491 924 answers to any question