0

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?

thedude19
  • 2,643
  • 5
  • 34
  • 43

1 Answers1

2

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?

matt b
  • 138,234
  • 66
  • 282
  • 345
  • I see exactly what you mean, but I'm unsure as to the correct way to do it. Basically, I'm looking to store 2 separate lists of MyType for each user, hence the USER_ID being the key. This obviously works fine if there is 1 list, but I'm not sure what changes I need to make to allow 2 lists to be stored of the same type. – thedude19 May 10 '11 at 15:54
  • 1
    Well, it might be helpful to ignore Hibernate and think of how you would model this, both in the table structure and with SQL queries - what column would serve as the link to the MyType table for list1 and what column would serve as the link for list2? You may also want to read over [the chapter in the Hibernate reference manual on associations](http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/associations.html), which includes lots of examples of different ways to model different types of associations between classes. – matt b May 10 '11 at 15:58
  • MyType has a boolean column that identifies which list the row should be in (along with USER_ID). Basically what I'm looking for is the select statements to be able to say 'SELECT m.* from MyType m where m.USER_ID = this.USER_ID and m.MY_BOOLEAN = true/false' That should do the trick I would think, but again unsure how this is done in hibernate mappings. – thedude19 May 10 '11 at 16:04