Hibernate SET元素的order by子句 [英] Hibernate SET element order-by clause

查看:128
本文介绍了Hibernate SET元素的order by子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,我可以找到我的安宁,因为您可以在fetch = select时在映射文件中的SET元素上设置order-by属性,但是如果您在创建查询。这会安全吗?

我的意思是,他们将结果抽到HashSet中,难道我不认为这些不能保证元素顺序?

解决方案

Hibernate实际上不会将结果抽取到 HashSet 中,将用它自己的 Set 实现替换任何现有的 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屋!

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