这是jpa片段代码:
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
@ManyToMany
@JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "author_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
private Set<Book> books = new HashSet<>();
。
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String isbn;
@OneToOne
private Publisher publisher;
@ManyToMany(mappedBy = "books")
private Set<Author> authors = new HashSet<>();
。
private void initData() {
Publisher publisher1 = new Publisher("Tabor");
publisherRepository.save(publisher1);
// Magdo, Madziu, Magdaleno
Author author1 = new Author("Magda", "Magdaleńska");
Book book1 = new Book("Tytuł książki 1", "123456abc", publisher1);
author1.getBooks().add(book1);
book1.getAuthors().add(author1);
bookRepository.save(book1);
authorRepository.save(author1);
// Cygan
Author author2 = new Author("Cygan", "Śniady");
Book book2 = new Book("Jak sprzedać dywan", "222", publisher1);
Book book3 = new Book("Jak sprzedać dywan2", "2223", publisher1);
author2.getBooks().add(book2);
author2.getBooks().add(book3);
book2.getAuthors().add(author2);
book3.getAuthors().add(author2);
bookRepository.save(book2);
bookRepository.save(book3);
authorRepository.save(author2);
}
在第三张表中,第三行缺少值(6,5)。
我不明白为什么。在author_id和book_id上设置了一个主键,而author_id上的一个外键不是唯一的,而book_id上的一个外键不是唯一的:
有人提示如何解决吗?
答案 0 :(得分:1)
我刚刚使用您的代码创建了一个GitHub存储库,以便能够对其进行测试。 (随时克隆它):
https://github.com/cristianprofile/stack_overflow_response/tree/master
工作正常:3个元组被添加到author_book中。