我有两个 Persistent Classes ,一个是书,一个是人,人可以拥有多本书,书也可以属于多个人,一个很简单的结构
我只是先学学如何使用hibernate,就写了以下hxm文件:
Book:
<hibernate-mapping> <class name="net.magician.test.testhibernate.bean.Book" table="book"> <id name="bookID" column="bookid" type="int" unsaved-value="null"> <generator class="identity"/> </id> <list name="persons" table="bookperson" inverse="true" lazy="true"> <key column="bookid" /> <index column="personid" /> <many-to-many column="personid" class="net.magician.test.testhibernate.bean.Person" /> </list> </class>
</hibernate-mapping>
|
Person:
<hibernate-mapping> <class name="net.magician.test.testhibernate.bean.Person" dynamic-update="false" dynamic-insert="false"> <id name="personID" column="personid" type="int" unsaved-value="null"> <generator class="identity"/> </id> <list name="books" table="bookperson" inverse="true" lazy="true"> <key column="personid" /> <index column="bookid" /> <many-to-many column="bookid" class="net.magician.test.testhibernate.bean.Book" /> </list> </class> </hibernate-mapping>
|
然后写了一个测试方法:
private static void testCreateBookAndPerson() throws Exception { Collection persons = new ArrayList); Book book = new Book(); book.setBuyTime(new Date()); for (int i=100;i<110;i++) { Person ptemp = (Person)session.load(Person.class , new Integer(i)); persons.add(ptemp); } book.setPersons(persons); session.save(book); }
|
person表已经有足够的数据
但我执行该方法时,book会成功插入数据库,但bookperson这个中间表里什么数据也没有
这里是SchemaExport生成的表文件:
create table book ( bookid INTEGER NOT NULL AUTO_INCREMENT, primary key (bookid) )
create table bookperson ( personid INTEGER not null, bookid INTEGER not null, primary key (bookid, personid) )
create table Person ( personid INTEGER NOT NULL AUTO_INCREMENT, primary key (personid) )
|
希望高手能帮忙解决一下
顺带提一个小问题,为什么update方法一定要用tx.commit()来完成操作?而其他的不用?我把update和insert都设为ture了,比如:
<hibernate-mapping> <class name="net.magician.test.testhibernate.bean.Province" dynamic-update="true" dynamic-insert="true"> <id name="provinceID" column="provinceid" type="int" unsaved-value="null"> <generator class="identity"/> </id>
<property name="provinceName" type="java.lang.String" update="true" insert="true" column="provincename" length="20" /> </class> </hibernate-mapping>
|
多谢各位了