Ordering return of Child objects in JPA query

If you are using springboot and jpa here's the example

in parent class add the code like below

@OneToMany(mappedBy = "user")
@OrderBy(value = "position desc ")
private List<UserAddresses> userAddresses;

in the above code, position is the field name in UserAddresses Class and desc is the order. You can pass either asc or desc like in sql order by.


For preserving order, use TreeSet. As far as, sorting of a collection inside parent is concerned, just do it in your code using Comparator.

Well, try this on your collection definition in your parent entity class. I hope you are getting my point.

You can use this JPA annotation,

@javax.persistence.OrderBy(value = "fieldName")

or this Hibernate specific,

@org.hibernate.annotations.OrderBy(clause = "FIELD_NAME asc")

and you can also use this,

@org.hibernate.annotations.Sort(type = SortType.NATURAL)

or

@org.hibernate.annotations.Sort(type = SortType.COMPARATOR)

In the case of comparator, a comparator must be in place. Other might only work with String collections.


Adeel basically has this nailed. You can also use those with a List which might be important if your collections contain the same entity more than once.