我是新手。我想在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>
在main类中创建如下表:
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. 在main类中我有:
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]
请guide.thanks。
-
如果使用SchemaExport(又名hbm2ddl), hibernate可以自动生成关系表(
Book_Author
)给你。您可以在hibernate.cfg.xml
中这样配置:<property name="hibernate.hbm2ddl.auto">create-drop</property>
-
我看到你用
<generator class="assigned"/>
作为你的id。在这种情况下,你必须手动分配id;如果不这样做,hibernate将抛出该异常。