最终我认为级联最适合处理删除所有子关系的情况,但我仍然认为这是一个复杂的注释,大多数人都不太了解。我认为如果Book实体拥有作者和流派关系,那么ORM别无选择,只能在删除一本书时删除关系。
当我设置一个简单的 springboot 项目时,它似乎可以解决所有这些问题。
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Author {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@ManyToMany(mappedBy = "authors")
@lombok.ToString.Exclude
private Set<Book> books;
}
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Genre {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "genres")
@lombok.ToString.Exclude
private Set<Book> books;
}
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Book {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
private Set<Author> authors;
@ManyToMany
private Set<Genre> genres;
}
还有一个简单的例子:
Author author = authorRepository.save(Author.builder().build());
Genre genre = genreRepository.save(Genre.builder().build());
Book book = bookRepository.save(Book.builder().authors(Collections.singleton(author)).genres(Collections.singleton(genre)).build());
System.out.println(book);
bookRepository.delete(bookRepository.getOne(book.getId()));
日志似乎表明,当一本书被删除时,作者和流派被清理了。
Hibernate: insert into author (id) values (null)
Hibernate: insert into genre (id) values (null)
Hibernate: insert into book (id) values (null)
Hibernate: insert into book_authors (books_id, authors_id) values (?, ?)
Hibernate: insert into book_genres (books_id, genres_id) values (?, ?)
Book(id=1, authors=[Author(id=1)], genres=[Genre(id=1)])
Hibernate: select book0_.id as id1_1_0_ from book book0_ where book0_.id=?
Hibernate: delete from book_authors where books_id=?
Hibernate: delete from book_genres where books_id=?
Hibernate: delete from book where id=?
我认为这就是你所质疑的。