带 inverse=true 的 Hibernate Collection of collection

Hibernate Collection of collection with inverse=true

我已经配置了我的 hbm.xml 里面有 2 个集合:一个集合的一个集合 inverse=true 为两个。

<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>

当我从 SETs 中提取我父亲的集合 C0 时,我发现我的 C1 集合中有很多元素,但不是我的 C2 集合中的所有项目每个项目仅包含一个元素(每个项目等待 2 个元素)。

这是一个错误吗?还是我错了?

如果有帮助,我可以把我的文件发给你。

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

提前致谢。

知道了!!!

出现问题是因为我在 class C2'ID 上忘记了一个属性的 equals 方法。

解释示例。

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 :我将缺少的 id3 添加到对象 C2 的 class ID 的 equals 方法中,一切都很好。

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

总结 :

  • 使用 hibernate,您可以根据需要使用 inverse=true 来收集 [of collection] 的集合。
  • 不要忘记覆盖集合的等号和哈希码。这保证了您的对象的唯一性并告诉 hibernate 如何管理它们。
  • 最重要的是:写equals和hashcode方法时要小心!不要忘记要比较的任何 ID :-)

就这些了。