Search code examples
javahibernatehbm

Mapping an object in Hibernate that has 2 lists causing problems


I'm trying to save an object that has 2 similar lists using a hbm.xml file. Below is my model object and HBM:

public class MyClass {

...

    private List<MyType> list;

    private List<MyType> otherList;

...

}

My HMB for this section is as follows:

    <list name="list" cascade="all-delete-orphan"
        lazy="false">
        <key column="USER_ID" />
        <list-index column="index" />
        <one-to-many class="path.to.MyType" />
    </list>

    <list name="otherList" cascade="all-delete-orphan"
        lazy="false">
        <key column="USER_ID" />
        <list-index column="index" />
        <one-to-many class="path.to.MyType" />
    </list>

However, when this object gets populated from the database, whatever I expect to be in 'list' is also showing up in 'otherList'. I imagine I'm missing a simple configuration change to allow hibernate to store these 2 lists properly, but I can't figure it out.

Any help?


Solution

  • The <list>s contain the same content because you are telling Hibernate to map the same class (path.to.MyType) using the same <key column="USER_ID"> in both instances. Are you sure you haven't made an error in the Hibernate mapping?

    Conceptually, what Hibernate will do to materialize these collections is issue a query like

    SELECT m.* from MyType m where m.USER_ID = this.USER_ID
    

    If you tell Hibernate to use the same query to map both list and otherList, how can it return different results for the same query?