Search code examples
javaxmlhibernateone-to-manyhibernate-onetomany

how to set Multiple one to many relation with same column hibernate


There are two entities.

  1. Route (Arrival, ArrivalID and Departure , DepartureID) as Location
  2. Location (Arrivals , Departures ) as Route

Location will have 2 one to many relationship with route table.

I am trying to set.

Route.xml

 <many-to-one name="departure" class="com.nakisa.agency.Location" fetch="select" insert="false" update="false">
        <column name="locationID" not-null="true" />
    </many-to-one>

     <many-to-one name="arrival" class="com.nakisa.agency.Location" fetch="select" insert="false" update="false">
        <column name="locationID" not-null="true" />
    </many-to-one>

Location.xml

<set name="arrivals" table="Routes" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="arrivalID" not-null="true" />
            </key>
            <one-to-many class="com.nakisa.agency.Route" />
        </set>


        <set name="departures" table="Routes" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="departureID" not-null="true" />
            </key>
            <one-to-many class="com.nakisa.agency.Route" />
        </set>

I'm getting error as departureID is null even i set departureID there in route.

How to correct these mappings in order to work


Solution

  • I think you have problem with fetching:

    Lazy="true|false" controls whether an association is loaded eagerly or on demand. fetch="select|subselect|join|batch" controls how is that entity or collection loaded, when it's required to be loaded.

    With lazy="true" and fetch="select" Hibernate will lazy load the collection and will load it with a select. If you set lazy="false", the same select will be executed, the difference will be that it will get executed eagerly. Hope this makes sense.

    Try to set lazy="false", and then see if your departureID is still null.