我正在尝试在2个表之间实现单向多对多关系,如下所示:
@Entity
@Table(name="Book")
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="book_name")
private String bookName;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_author",
joinColumns = { @JoinColumn(name = "book_id") },
inverseJoinColumns = { @JoinColumn(name = "author_id") })
private List<Author> bookAuthors;
//getter and setters here
}
我的作者课程如下:
@Entity
@Table(name="Author")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="author_name")
private String authorName;
@Column(name="author_description")
private String authorDesc;
//getter setters here
}
用于保存数据的代码如下(请注意,我要在拥有实体的book对象上调用save):
//create book
Book book1 = new Book();
book1.setBookName("Book1");
//create and set Author info
Author author1 = new Author();
author1.setAuthorName("a1");
author1.setAuthorDesc("a1 description");
Author author2 = new Author();
author2.setAuthorName("a2");
author2.setAuthorDesc("a2 description");
List<Author> authorsList1 = new ArrayList<Author>();
authorsList1.add(author1);
authorsList1.add(author2);
book1.setBookAuthors(authorsList1);
//save book
session.save(book1);
这将执行以下休眠代码:
Hibernate: insert into Book (book_name, category_id, numOfCopies) values (?, ?, ?)
Hibernate: insert into Author (author_description, author_name) values (?, ?)
Hibernate: insert into Author (author_description, author_name) values (?, ?)
查询表时,我在Book and Author表中看到数据,但在联接表中看不到数据,即Book_author。知道我做错了什么吗?
我提到了以下示例: http://websystique.com/hibernate/hibernate-many-to-many-unidirectional-annotation-example/
我什至尝试通过将书籍添加到作者类中来将代码更改为双向映射,如下所示:
@ManyToMany(mappedBy="bookAuthors")
private List<Book> books;
,但是仍然没有数据保存到联接表中。
任何帮助将不胜感激!
谢谢!