【问题标题】:Hibernate many-valued association best practicesHibernate 多值关联最佳实践
【发布时间】:2017-05-02 09:05:23
【问题描述】:

stackoverflow 上有很多关于在 Hibernate 实体中使用 ListSet 的问题。我的问题略有不同(或者可能相同,但我还无法理解)。

如果我阅读了 Hibernate 文档,他们建议在这里使用 Set 进行多值关联 http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#persistent-classes-equalshashcode

Quoting from above documentation link:

 You have to override the equals() and hashCode() methods if you:

 - intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations); 
 - and intend to use reattachment of detached instances

直到 Hibernate 4.3。但是在以后的版本中,我不再看到那个声明了(http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#mapping-model-pojo-equalshashcode

所以我的问题是

  • 为什么 Hibernate 建议在 Hibernate 4 之前使用 Set 而不是 List
  • 由于我在 Hibernate 5 中没有看到该建议,是否意味着它不再有效?

谢谢!!

【问题讨论】:

  • 我不认为你应该做的只有一个规则,但用法取决于你的需要。我建议阅读此内容,但您可能已经阅读过 - stackoverflow.com/questions/6562673/…
  • 感谢您的评论。我读了那个问题,还有其他一些问题。我也同意不只是一个单一的规则。我试图理解为什么 Hibernate 推荐使用 Sets。我认为这样的建议背后应该有一些原因。

标签: java list hibernate set hibernate-mapping


【解决方案1】:

回答你的第一个问题:

为什么 Hibernate 建议使用 Set 而不是 List 直到 Hibernate 4?

我将首先指出ListSet之间的主要区别:

  • List 是有序集合,而 Set 不是,但请注意,虽然 List 是有序集合,但如果您的对象中未指定索引列,则不会对其进行排序。
  • Set 不允许重复,而 List 允许。

第二点解释了在List 上使用Set 的建议,即使Hibernate documentation itself says that lists and bags are more efficient than sets 也是如此。

事实上,在双向关系中使用List 的问题是当你在父关联上调用合并操作时,它会插入重复的子节点,这似乎是a bug in older Hibernate versions,你可以在以下位置阅读有关此问题的更多信息:

Hibernate Facts: Favoring bidirectional Set(s) vs List(s)

回答你的第二个问题:

由于我在 Hibernate 5 中没有看到该建议,是否意味着它不再有效?

我们无法推断这一事实,但我认为这个错误已在 Hibernate 5 上得到修复,这就是我们不再看到此建议的原因,但这只是一个假设

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多