0
0
SpringbootHow-ToBeginner · 3 min read

How to Use Sort in Spring Data: Simple Guide with Examples

In Spring Data, you use the Sort class to specify the order of query results by passing it to repository methods like findAll(Sort sort). You create a Sort object with properties and directions (ascending or descending) to control sorting behavior.
📐

Syntax

The Sort class in Spring Data is used to define sorting rules for queries. You create a Sort object by specifying the direction (ascending or descending) and the property name(s) to sort by.

Common usage patterns include:

  • Sort.by(Direction.ASC, "propertyName") - Sort ascending by a property.
  • Sort.by(Direction.DESC, "propertyName") - Sort descending by a property.
  • Sort.by("property1", "property2") - Sort ascending by multiple properties.

You then pass this Sort object to repository methods like findAll(Sort sort) to get sorted results.

java
Sort sort = Sort.by(Sort.Direction.ASC, "name");
List<Entity> results = repository.findAll(sort);
💻

Example

This example shows how to sort a list of users by their last name in ascending order using Spring Data JPA.

java
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

// Entity class
public class User {
    private Long id;
    private String firstName;
    private String lastName;
    // getters and setters
}

// Repository interface
public interface UserRepository extends JpaRepository<User, Long> {
}

// Usage in a service or controller
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getUsersSortedByLastName() {
        Sort sort = Sort.by(Sort.Direction.ASC, "lastName");
        return userRepository.findAll(sort);
    }
}
Output
Returns a list of User objects sorted by lastName in ascending order.
⚠️

Common Pitfalls

Common mistakes when using Sort in Spring Data include:

  • Using property names that do not match entity fields, causing runtime errors.
  • Forgetting to specify the direction, which defaults to ascending but can cause confusion.
  • Passing null or an empty Sort object, which results in unsorted results.
  • Trying to sort on nested properties without proper naming (use dot notation like address.city).

Always verify property names and directions to avoid unexpected behavior.

java
/* Wrong: property name typo */
Sort sortWrong = Sort.by("last_name"); // 'last_name' does not match 'lastName'

/* Right: correct property name */
Sort sortRight = Sort.by("lastName");
📊

Quick Reference

UsageDescription
Sort.by(Direction.ASC, "property")Sort ascending by a single property
Sort.by(Direction.DESC, "property")Sort descending by a single property
Sort.by("prop1", "prop2")Sort ascending by multiple properties
repository.findAll(Sort sort)Fetch all entities sorted as specified
Sort.by("nested.property")Sort by nested property using dot notation

Key Takeaways

Use the Sort class to specify sorting direction and properties in Spring Data queries.
Pass the Sort object to repository methods like findAll to get sorted results.
Always use exact entity property names to avoid runtime errors.
You can sort by multiple properties by listing them in Sort.by().
Use dot notation to sort by nested object properties.