Sorting Query Results with Spring Data

1. Introduction

In this tutorial, we’re going to learn how to sort query results with Spring Data.

First, we’ll take a look at the schema of the data that want to query and sort.

And then, we’ll dive right into how to achieve that Spring Data.

Let’s get started!

2. The Test Data

Below we have some example data. Although we have represented it here as a table we could use any one of the databases supported by Spring Data to persist it.

The question we want to answer is, “Who is occupying which seat on the airline?” but to make that more user-friendly we want to sort by seat number.

First NameLast NameSeat Number
JillSmith50
EveJackson94
FredBloggs22
RickiBobbie36
SiyaKolisi85

3. Domain

To create a Spring Data Repository we need to provide a domain class as well as an id type.

Here we’ve modeled our passenger as a JPA entity, but we could just as easily have modeled it as a MongoDB document or any other model abstraction:

@Entity
class Passenger {

    @Id
    @GeneratedValue
    @Column(nullable = false)
    private Long id;

    @Basic(optional = false)
    @Column(nullable = false)
    private String firstName;

    @Basic(optional = false)
    @Column(nullable = false)
    private String lastName;

    @Basic(optional = false)
    @Column(nullable = false)
    private int seatNumber;

    // constructor, getters etc.
}

4. Sorting with Spring Data

We have a few different options at our disposal for sorting with Spring Data.

4.1. Sorting With the OrderBy Method Keyword

One option would be to use Spring Data’s method derivation whereby the query is generated from the method name and signature.

All we need to do here to sort our data is include the keyword OrderBy in our method name along with the property name(s) and direction (Asc or Desc) by which we want to sort.

We can use this convention to create a query that returns our passengers in ascending order by seat number:

interface PassengerRepository extends JpaRepository<Passenger, Long> {

    List<Passenger> findByOrderBySeatNumberAsc();
}

We can also combine this keyword with all the standard Spring Data method names.

Let’s see an example of a method that finds passengers by last name and orders by seat number:

List<Passenger> findByLastNameOrderBySeatNumberAsc(String lastName);

4.2. Sorting with a Sort Parameter

Our second option is to include a Sort parameter specifying the property name(s) and direction by which we want to sort:

List<Passenger> passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber"));

In this case, we’re using the findAll() method and adding the Sort option when calling it.

We can also add this parameter to a new method definition:

List<Passenger> findByLastName(String lastName, Sort sort);

Finally, if perhaps we are paging, we can specify our sort in a Pageable object:

Page<Passenger> page = repository.findAll(PageRequest.of(0, 1, Sort.by(Sort.Direction.ASC, "seatNumber")));

5. Conclusion

We have two easy options for sorting data with Spring Data through method derivation using the OrderBy keyword or using the Sort object as a method parameter.

As always, you can find the code over on GitHub.

Related posts:

Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Java Program to Implement Ternary Search Algorithm
Object cloning trong java
Guide to CountDownLatch in Java
Jackson Date
Documenting a Spring REST API Using OpenAPI 3.0
Java Program to Encode a Message Using Playfair Cipher
Remove the First Element from a List
Different Ways to Capture Java Heap Dumps
Java Program to Implement Karatsuba Multiplication Algorithm
Mapping Nested Values with Jackson
ClassNotFoundException vs NoClassDefFoundError
Introduction to the Java ArrayDeque
Convert XML to JSON Using Jackson
Java Program to Implement Lloyd’s Algorithm
Java Program to Implement Bloom Filter
A Guide to Concurrent Queues in Java
Setting a Request Timeout for a Spring REST API
A Guide to the Java ExecutorService
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Phân biệt JVM, JRE, JDK
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java 8 Stream API Analogies in Kotlin
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Java Program to Delete a Particular Node in a Tree Without Using Recursion
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Java Program to implement Associate Array
Java Program to add two large numbers using Linked List
Stack Memory and Heap Space in Java
OAuth2 Remember Me with Refresh Token
Spring WebClient Requests with Parameters