Hibernate SET元素的order by子句 [英] Hibernate SET element order-by clause
问题描述
我想知道,我可以找到我的安宁,因为您可以在fetch = select时在映射文件中的SET元素上设置order-by属性,但是如果您在创建查询。这会安全吗?
我的意思是,他们将结果抽到HashSet中,难道我不认为这些不能保证元素顺序?
Hibernate实际上不会将结果抽取到 HashSet
中,将用它自己的 HashSet
。
当你通过调用persist()使实例持久化时,Hibernate实际上会用一个Hibernate自己实现Set的实例替换HashSet。
http://docs.jboss .org / hibernate / core / 3.6 / reference / en-US / html / collections.html b
order by属性,那么它不会使用 HashSet
,它可能会使用 LinkedHashSet
来代替。从上面引用的同一个文档中引用此:
如果您希望数据库本身对集合元素进行排序,请使用该命令 - 通过设置,行李或地图映射的属性。此解决方案使用LinkedHashSet或LinkedHashMap实现,并在SQL查询中执行排序,而不是在内存中执行。
因此,Hibernate将安全地维护项目在 Set
中的顺序 - 但在创建新对象并保留它们时要小心。如果你在一个新的对象中使用 HashSet
而不是 LinkedHashSet
,那么Hibernate会保持你的集合基本上是随机的订单,因为 HashSet
不保证元素顺序。
I was wondering, I can find my peace with the fact that you can set the order-by attribute on a SET element in the mappings file when fetch=select, but if you fetch everything at the time when you are creating the query. Will this be safe?
I mean, they are pumping the results into a HashSet, aren't I thought those couldn't guarantee element order?
Hibernate doesn't actually pump results into a HashSet
, it will replace any existing HashSet
with its own implementation of Set
.
When you make the instance persistent, by calling persist(), Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set.
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html
If you use the order-by attribute then it won't use a HashSet
, probably it will use a LinkedHashSet
instead. Refer to this, from the same document as I quoted above:
If you want the database itself to order the collection elements, use the order-by attribute of set, bag or map mappings. This solution is implemented using LinkedHashSet or LinkedHashMap and performs the ordering in the SQL query and not in the memory.
So Hibernate will safely maintain the order of items in a Set
— but be careful when you create new objects and persist them. If you use a HashSet
instead of a LinkedHashSet
in a new object, then Hibernate would persist your set in an essentially random order, because HashSet
doesn't guarantee element order.
这篇关于Hibernate SET元素的order by子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!