I was reading an article about mapping collections and ordering them. and there was a sentence:
You shouldn’t use it with SortedSets to avoid an additional sorting of the already ordered entities.
I couldn't understand this statement. it was vague for me. what is that additional sorting?
and I also saw many examples about this issue and non of them use @OrderBy
with SortedSet
. and all of them were trying to use SortedSet
with @SortNatural
and @Sort
.
Why no one use @OrderBy
with SortedSet
?
however, I saw a lot of examples which use @OrderBy
with SortedMap
? what is the difference between these two(SortedSet
& SortedMap
) when we're trying to use @OrderBy
?
@OrderBy
results in an ORDER BY
clause appearing in the generated SQL. ORDER BY
clauses do not modify the results you get; it merely modifies the order in which you get the results.
Most sets completely disregard the order in which you put elements into it:
HashSet<String> set = new HashSet<String>();
set.add("Hello"); // line 1
set.add("World"); // line 2
for (String elem : set) System.out.println(elem);
The above arbitrarily prints 'Hello' then 'World' or 'World', then 'Hello' (The order depends on the hashcode which is an irrelevant detail. Hence the word 'arbitrary' - it's not random - you can't rely on it being different and you definitely should not rely on this for anywhere randomness is required, so there is an order to it, but that order has no meaning. It's arbitrary). Also, swapping line 1 and 2 around has no effect on the output of this code.
Most sets work this way (that the order in which you put things in have no bearing on the result; only what you put in, not in what order you put them in). Specifically, all SortedSets work that way, because by definition a sorted set will keep its contents sorted at all times, which trivially means the order in which you put elements into it is irrelevant.
And, here's the thing: If you ask your DB to spend time ordering things, so that you then take the result of this and shove the elements into a set that disregards the order you gave it its elements, that's.. stupid. A pointless waste of time. So, using @OrderBy
is a silly thing to do for most sets, and is a silly thing to do for all SortedSets
. The only commonly used set in java that it is useful for, is LinkedHashSet
, which is explicitly defined to maintain the order in which you put elements into it. Even though HashSet
is not a SortedSet
, using @OrderBy
to then put the elements into a HashSet
'works' and is silly. The @OrderBy
part has no effect whatsoever other than waste DB resources. Same for any SortedSet
, and same for almost all other things that implement Set (except LinkedHashSet
and very few other ones whose docs explicitly indicate they retain insertion order).