关于stackoverflow有很多关于在Hibernate实体中使用List
与Set
的问题。我的问题略有不同(或者可能相同,但我还无法理解)。
如果我阅读了 Hibernate 文档,他们建议在这里 http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#persistent-classes-equalshashcode 将Set
用于多值关联。
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建议使用
Set
而不是List
直到Hibernate4? - 由于我在Hibernate 5中没有看到该建议,这是否意味着它不再有效?
谢谢!!
好吧,回答你的第一个问题:
为什么Hibernate建议使用Set而不是List直到Hibernate 4?
我将首先指出List
和Set
之间的主要区别:
List
是有序集合,而Set
不是,但请注意,虽然List
是有序集合,但如果对象中未指定索引列,则不会对其进行排序。Set
不允许重复,而List
允许。
第二点解释了在List
上使用Set
的建议,即使Hibernate文档本身说列表和包比集合更有效。
实际上,在双向关系中使用List
的问题在于,当您在父关联上调用合并操作时,它会插入重复的子项,这似乎是旧Hibernate版本中的错误,您可以在以下位置阅读有关此问题的更多信息:
休眠事实:支持双向集合与列表
回答你的第二个问题:
由于我在Hibernate 5中没有看到该建议,这是否意味着它不再有效?
我们不能在这个事实中进行推断,但我认为这个错误在 Hibernate 5 上得到了修复,这就是为什么我们不再看到这个建议,但这只是一个假设。