OrderBy in Java Persistence with Spring Data and Hibernate

In Java Persistence with Spring Data and Hibernate, ordering query results is a common requirement. The orderBy method in Querydsl and the @OrderBy annotation in Hibernate provide mechanisms to achieve this.

Querydsl's orderBy Method

The orderBy method in Querydsl is used to order query results based on specified criteria. It can receive multiple arguments to define the order, such as ascending or descending order for specific fields. For example, to order User instances by username, you can use the following code:

[Listing 19.12 Ordering User instances by username](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-19/42)

@Test
void testOrderByUsername() {

    List<User> users = queryFactory.selectFrom(QUser.user)                 #1
            .orderBy(QUser.user.username.asc())                            #2
            .fetch();                                                      #3

    assertAll(                                                             #4
            () -> assertEquals(users.size(), 10),                          #4
            () -> assertEquals("beth", users.get(0).getUsername()),        #4
            () -> assertEquals("burk", users.get(1).getUsername()),        #4
            () -> assertEquals("mike", users.get(8).getUsername()),        #4
            () -> assertEquals("stephanie", users.get(9).getUsername())    #4
    );                                                                     #4
}
  • #1: Start building the query using the selectFrom method belonging to the JPAQueryFactory class. This method will get the created Q-type instance QUser.user as an argument and will return a JPAQuery.
  • #2: Order the results by username, ascending. The orderBy method is overloaded and can receive multiple criteria to order by.
  • #3: The fetch method will fetch the list of User instances.
  • #4: Verify that the fetched data is the expected data.

Hibernate's @OrderBy Annotation

In Hibernate, the @OrderBy annotation is used to specify the order of elements in a collection when they are loaded from the database. This annotation can be applied to collections such as Set, List, and Map.

Using LinkedHashSet for Ordered Collections

When using a LinkedHashSet, Hibernate applies an ORDER BY clause to the SQL statement that loads the collection. This is done using the proprietary @org.hibernate.annotations.OrderBy annotation. For example:

[Listing 8.9 LinkedHashSet offers insertion order for iteration](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-19/42)

@Entity
public class Item {
    // . . .

    @ElementCollection
    @CollectionTable(name = "IMAGE")
    @Column(name = "FILENAME")
    @org.hibernate.annotations.OrderBy(clause = "FILENAME desc")
    private Set<String> images = new LinkedHashSet<>();

Using ArrayList for Ordered Collections

Similarly, an ArrayList can be used to maintain a stable iteration order:

[Listing 8.10 ArrayList provides a stable iteration order](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-19/42)

@Entity
public class Item {
    // . . .

    @ElementCollection
    @CollectionTable(name = "IMAGE")
    @Column(name = "FILENAME")
    @GenericGenerator(name = "sequence_gen", strategy = "sequence")
    @org.hibernate.annotations.CollectionId(
            columns = @Column(name = "IMAGE_ID"),
            type = @org.hibernate.annotations.Type(type = "long"),
            generator = "sequence_gen")
    @org.hibernate.annotations.OrderBy(clause = "FILENAME desc")
    private Collection<String> images = new ArrayList<>();

Using LinkedHashMap for Ordered Key/Value Pairs

For key/value pairs, a LinkedHashMap can be used:

[Listing 8.11 LinkedHashMap keeps key/value pairs in order](https://livebook.manning.com/book/java-persistence-with-spring-data-and-hibernate/chapter-19/42)

@Entity
public class Item {
    // . . .

    @ElementCollection
    @CollectionTable(name = "IMAGE")
    @MapKeyColumn(name = "FILENAME")
    @Column(name = "IMAGENAME")
    @org.hibernate.annotations.OrderBy(clause = "FILENAME desc")
    private Map<String, String> images = new LinkedHashMap<>();

Considerations

It's important to note that the elements of ordered collections are only in the desired order when they’re loaded. As soon as elements are added or removed, the iteration order might differ from the specified order. This behavior is inherent to the collection types used, such as LinkedHashSet, ArrayList, and LinkedHashMap.

FAQ (Frequently asked questions)

Can the orderBy method in Querydsl handle multiple arguments?