Kevin Kamer
Kevin Kamer

Reputation: 99

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>

Upvotes: 0

Views: 831

Answers (2)

Kevin Kamer
Kevin Kamer

Reputation: 99

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

Upvotes: 0

Pierre-Henri
Pierre-Henri

Reputation: 1505

You forgot the inverse="true" on one side of the bidirectional relationship.

Upvotes: 3

Related Questions