Reputation: 14044
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?
Upvotes: 1
Views: 6895
Reputation: 7139
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.
Upvotes: 4