Search code examples
hibernatecollectionsinverse

Hibernate Collection of collection with inverse=true


I have configured my hbm.xml with 2 collections inside: a collection of a collection with inverse=true for the two.

<class class="C0">
<properties/>
   <set inverse="true">
     <one-to-many class="C1"/>
   </set>
</class>

<class class="C1">
   <properties/>
   <set inverse="true" >
     <one-to-many class="C2"/>
   </set>
</class>

<class class="C2">
  ...
  <!-- No collection there -->
</class>

When I fecth my father collection C0 through SETs I find good number of elements inside my C1 collection BUT not all item inside my C2 collection which contains only one element per item (waiting for 2 elements per each item).

Is it a bug ? Or am I wrong ?

I can send you my file if that can help.

Hibernate version : hibernate-core-4.3.8.Final.jar
C3P0 : hibernate-c3p0-4.3.8.Final.jar
JAVA 8.0

Thank you in advance.


Solution

  • Got it !!!

    The problem occurs because of my equals method on class C2'ID where i have forgotten an attribute.

    Example for explanation.

    My object to be compared has this composed id : id1 (of class C0), id2 (of class C1), id3 (of class C2).

    and my equals method of class ID of C2 was like this

    id1.equals(other.id1) && id2.equals(other.id2)
    

    so when hibernate get to database, C2 objects (id1, id2, id3), he compares hese ids and says that obj1.id equals to obj2.id which is true the two objects are the same. So hibernate chooses only one of two objects. This is why i had one object.

    SOLUTION : I add to my equals method of class ID of object C2 the lacking id3 and everything gones GOOD.

    id1.equals(other.id1) && id2.equals(other.id2) && id3.equals(other.id3)
    

    TO SUM UP :

    • With hibernate you can make collection of collection [of collection] with inverse=true as you want.
    • Don't forget to override equals and hashcode for collections. This garantee the uniqueness for your objects and tell hibernate how to manage with them.
    • The most important: be careful when you write you equals and hashcode method! don't forget any IDs to be compared :-)

    That's all.