1

我正在尝试进行多对多映射,但是下面的代码有问题。使用此代码创建的表看起来不错,外键添加正确。当我尝试创建相关对象并将它们保存到数据库时,就会出现问题。午餐应用程序后,我在 KURS 表中有一行,在 KATEGORIE 表中有一行,但第三个表 - KURSY_KATEGORIE 是空的:(

表格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();
4

1 回答 1

2

尝试改变:

<set cascade="save-update" name="kursy" table="KURSY_KATEGORIE" inverse="true" lazy="true">

到:

<set cascade="save-update" name="kursy" table="KURSY_KATEGORIE" lazy="true">

和:

<set cascade="save-update" name="kategorie" inverse="true" lazy="true" table="KURSY_KATEGORIE">

到:

<set name="kategorie" inverse="true" lazy="true" table="KURSY_KATEGORIE">

我很惊讶hibernate不会为无效配置抛出异常(两端不能设置为反向 - 一个必须是所有者)

于 2012-11-19T18:44:11.473 回答