简体   繁体   中英

Hibernate Many-to-Many doesn't work

I try to understand hibernate but it is very hard.

I have a problem now that i don't really understand. Its about the many-to-many relations in my mapping file. If I save an object it wont save the "many" in my DB but it wont save it. I think it is in my mapping but i don't see it.

It's about flight and staff on the plane. When I save the plane the staff members must be save with it. But that wont happen.

Here is my mapping of both: The Flight mapping:

<?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 28-sep-2012 11:49:37 by Hibernate Tools 3.2.1.GA -->
     <hibernate-mapping>
    <class name="model.Flight" table="flights" catalog="flyaway_db">

    <id name="number" type="int">
        <column name="FlightNumber" />
        <generator class="assigned" />
    </id>

    <set name="staffs" table="flightstaff" cascade="save-update"> 
        <key>
            <column name="FlightNumber" not-null="true" />
        </key>
        <many-to-many class="model.Staff">
            <column name="StaffNumber" length="5" not-null="true" />
        </many-to-many>
    </set>

</class>
</hibernate-mapping>

The staff mapping:

<?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 28-sep-2012 11:49:37 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="model.Staff" table="staff" catalog="flyaway_db">

    <id name="staffNumber" type="string">
        <column name="StaffNumber" length="5" />
        <generator class="assigned" />
    </id>

    <set name="flightses" table="flightstaff" cascade="save-update">
        <key>
            <column name="StaffNumber" length="5" not-null="true" />
        </key>
        <many-to-many class="model.Flight">
            <column name="FlightNumber" not-null="true" />
        </many-to-many>
    </set>
</class>
</hibernate-mapping>

您忘记了bidirectional关系一侧的inverse="true"

Sorry for all the question but it was the model that wasn't correct! and i think Pache answer also helped! Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM