1
我正在嘗試執行多對多映射,但遇到下面的代碼有問題。使用此代碼創建的表看起來很好,外鍵已正確添加。當我嘗試創建相關對象並將它們保存到數據庫時,會發生此問題。吃午飯的應用程序後,我有表KURS一行,在表KATEGORIE一列,但第三個表 - KURSY_KATEGORIE是空的:(爲什麼我的連接表爲空? (使用Hibernate映射多對多)
表1:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2012-11-08 11:48:42 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="model.Kurs" table="KURS" node="kurs">
<id name="id" type="long">
<column name="ID_KURSU" />
<generator class="native" />
</id>
...
<set cascade="save-update" name="kategorie" inverse="true" lazy="true" table="KURSY_KATEGORIE">
<key foreign-key="FK_KATEGORIE_KURSY">
<column name="ID_KURSU" />
</key>
<many-to-many class="model.Kategoria" column="ID_KATEGORI"/>
</set>
</class>
</hibernate-mapping>
表2:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2012-11-08 11:48:42 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="model.Kategoria" table="KATEGORIA" node="kategoria">
<id name="id" type="long">
<column name="ID_KATEGORI" />
<generator class="native" />
</id>
...
<set cascade="save-update" name="kursy" table="KURSY_KATEGORIE" inverse="true" lazy="true">
<key foreign-key="FK_KURSY_KATEGORIE">
<column name="ID_KATEGORI" />
</key>
<many-to-many class="model.Kurs" column="ID_KURSU"/>
</set>
</class>
</hibernate-mapping>
而且java文件:
Session session = SESSION_FACTORY.openSession();
Transaction tx = session.beginTransaction();
GregorianCalendar Data_rozp = new GregorianCalendar();
Kategoria cat1 = new Kategoria("Kategoria1");
Set<Kategoria> kategorie = new HashSet<Kategoria>(3);
kategorie.add(cat1);
Kurs k1 = new Kurs(Data_rozp, "kurs1", 100);
Set<Kurs> kursy = new HashSet<Kurs>(1);
kursy.add(k1);
cat1.setKursy(kursy);
k1.setKategorie(kategorie);
session.save(cat1);
session.save(k1);
tx.commit();
session.close();
非常感謝:]現在它工作:D – Sirtarius