我是新来的冬眠。我想在netbeans中使用 hibernate 在书籍和作者之间创建多对多的连接。我看到的所有示例都是针对 Eclipse 而我找不到我的问题的答案。我的 Book.hbm.xml 是:
<hibernate-mapping>
<class name="Book" table="books">
<id name="bookId" type="int" column="BookID">
<generator class="assigned"/>
</id>
<property name="isbn" column="Isbn" type="string"/>
<property name="title" column="Title" type="string"/>
<property name="bookPicPath" column="BookPicPath" type="string"/>
<property name="summary" column="Summary" type="string"/>
<property name="genry" column="Genry" type="string"/>
<property name="parentGenry" column="ParentGenry" type="string"/>
<set name="authors" table="Book_Author" cascade="all">
<key column="BookID" />
<many-to-many column="AuthorID" class="Author" />
</set>
</class>
</hibernate-mapping>
Author.hbm.xml 是:
<hibernate-mapping>
<class name="Author" table="authors">
<id name="authorId" type="int" column="AuthorID">
<generator class="assigned"/>
</id>
<property name="fname" column="Fname" type="string"/>
<property name="lname" column="Lname" type="string"/>
<property name="biography" column="Biography" type="string"/>
<property name="gender" column="Gender" type="string"/>
<property name="website" column="Website" type="string"/>
<property name="authorPicPath" column="AuthorPicPath" type="string"/>
</class>
</hibernate-mapping>
在主类中,我创建这样的表:
HibernateUtil.droptable("drop table authors");
HibernateUtil.setup("create table authors ( AuthorID int, Fname VARCHAR(20), Lname VARCHAR(20), Biography VARCHAR(255), Gender VARCHAR(20), Website VARCHAR(255), AuthorPicPath VARCHAR(255))");
HibernateUtil.droptable("drop table books");
HibernateUtil.setup("create table books ( BookID int, Isbn VARCHAR(20), Title VARCHAR(255), BookPicPath VARCHAR(255), Summary VARCHAR(255), Genry VARCHAR(255), ParentGenry VARCHAR(255))");
我的问题:
1.在多对多关系中有一个连接表(Book_Author)。现在我必须手动完成还是hibernate自己创建?
2.在主课上我有:
SessionFactory sessions = new Configuration().configure().buildSessionFactory();
Session session = sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Set<Author> authors = new HashSet<Author>();
Author a1 = new Author("1","1","1","1","1","1");
Author a2 = new Author("2","2","2","2","2","2");
authors.add(a1);
authors.add(a2);
Book b1= new Book("a","a","a","a","a","a",authors);
session.save(b1);
tx.commit();
tx = null;
} catch ( HibernateException e ) {
if ( tx != null )
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
但是当我运行程序时,我看到以下错误:
a different object with the same identifier value was already associated with the session: [Author#0]
请指导。谢谢。