我想知道,当 fetch=select 时,您可以在映射文件中的 SET 元素上设置 order-by 属性,但如果您在创建询问。这样会安全吗?
我的意思是,他们正在将结果抽取到 HashSet 中,我不是认为它们不能保证元素顺序吗?
最佳答案
Hibernate 实际上不会将结果泵入 HashSet
, 它将替换任何现有的 HashSet
有自己的实现 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
如果您使用 order-by 属性,那么它不会使用 HashSet
, 可能会使用 LinkedHashSet
反而。请引用我在上面引用的同一文档中的内容:
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.
因此 Hibernate 将安全地维护 Set
中的项目顺序——但是当你创建新对象并持久化它们时要小心。如果您使用 HashSet
而不是 LinkedHashSet
在一个新对象中,那么 Hibernate 将以基本上随机的顺序保留你的集合,因为 HashSet
不保证元素顺序。
关于java - Hibernate SET 元素 order-by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7303170/