Hibernate:使用的最佳集合类型 - bag,idbag,set,list,map [英] Hibernate: best collection type to use - bag, idbag, set, list, map

查看:75
本文介绍了Hibernate:使用的最佳集合类型 - bag,idbag,set,list,map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Hibernate中进行一对多关联时,我正在寻找大多数人用作其集合类型的东西。我所维护的遗留应用程序专门使用包,但将它们保存为代码中的列表。关联的表有一个id字段,所以idbag似乎更合适,但文档建议使用Set。

编辑:我错误地引用了文档建议的设置。实际上,官方文件在所有收集类型上都是模糊的。我发现一些 网站似乎推断出Set是最常见的,而我正在阅读的Hibernate书明确地说了这些关于set的内容:


这是典型Hibernate应用程序中最常见的持久集合。 (请参阅Christian Bauer和Gavin King的'Java Persistence with Hibernate'一书第242页)

我猜这就是我投掷的东西,让我看看其他人在用什么。



编辑2:注意到Gavin King是Hibernate的创建者

解决方案

好了,经过一段时间,我找到了一个不使用Set作为集合类型的原因。由于hashcode / equals覆盖的问题以及hibernate持久化的方式,使用调用hashcode / equals的任何Java API函数是一个坏主意。持续比较持久性前后的对象是没有好方法的。坚持不依赖equals / hashcode的集合,比如 bag

更多信息:



http://community.jboss.org/wiki/EqualsandHashCode (这个链接使得它听起来像一个商业关键是要走的路,但完全阅读下一个链接,看看为什么这并不总是一个好主意)



https://forum.hibernate.org/viewtopic.php?f= 1& t = 928172 (阅读整个讨论,让你的头脑旋转)


I am looking for what most people use as their collection type when making one-to-many associations in Hibernate. The legacy application I am maintaining uses bags exclusively, but keeps them as lists in code. The tables associated have an id field, so an idbag seems more appropriate, but documentation recommends a Set.

EDIT: I mistakenly referenced that the documentation recommends a set. In reality, the official documentation is equally vague on all collection types. What I find is that some websites seem to infer that Set is the most common, and the Hibernate book I am reading explicitly says this about sets:

This is the most common persistent collection in a typical Hibernate application. (see: page 242 of 'Java Persistence with Hibernate' by Christian Bauer and Gavin King)

I guess that is what threw me and made me seek out what others are using.

EDIT2: note that Gavin King is the creator of Hibernate

解决方案

Ok, after quite some time I have found a reason NOT to use a Set as a collection type. Due to problems with the hashcode/equals overrides and the way hibernate persists, using any java API functionality that calls hashcode/equals is a bad idea. There is no good way to consistently compare objects pre- and post-persistence. Stick with collections that do not rely on equals/hashcode like bag.

More info here:

http://community.jboss.org/wiki/EqualsandHashCode (this link makes it sound like a business key is the way to go, but read the next link fully to see why that is not always a good idea)

https://forum.hibernate.org/viewtopic.php?f=1&t=928172 (read the whole discussion to make your head spin)

这篇关于Hibernate:使用的最佳集合类型 - bag,idbag,set,list,map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆