假设我有两张表(Books和Authors之间是多对多的关系)
BOOKS
id
book_name
AUTHORS
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不能为空
2) 如何使用序列生成器为关系表BOOKS_AUTHORS生成ID