让我有表格(书籍和作者有多对多关系)
书
id book_name
作者
id
author_name
BOOKS_AUTHORS
id
book_id
author_id
我将此表映射到实体上
class Books
{
@Id
long id;
@Column(name = "author_name")
String name;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "BOOKS_AUTHORS",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
List<Authots> authors;
// setter, getters, adder
}
class Authors
{
@Id
long id;
@Column(name = "author_name")
String name;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "BOOKS_AUTHORS",
joinColumns = @JoinColumn(name = "author_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
List<Books> books;
// setter, getters, adder
}
现在,我尝试下一步
public void addAuthor(final String bookName, final Author author)
{
final Book book = // get book from database by bookName
if (book == null)
throw new DataNotFoundException("Book not found :(");
author.addBook(book);
book.addAuthor(author);
entityManager.persist(author);
}
1) 我得到 BOOKS_AUTHORS 记录的 ID 不能为 NULL 的异常
2) 我如何为关系表 BOOKS_AUTHORS 生成 ID(序列生成器)