Write a query method for sorting in Spring Data JPA.

Spring Data JPA lets you express sorting directly in a derived query method name using the OrderBy keyword, followed by the entity property to sort on and an optional Asc or Desc suffix, without needing to write any JPQL.

Key Points: • The pattern is findBy...OrderBy<Property><Asc|Desc>, and Asc is the default if omitted. • Multiple sort properties can be chained, e.g. OrderByLastNameAscFirstNameDesc. • For dynamic, runtime-determined sorting, a Sort or Pageable parameter is more flexible than baking the order into the method name. • Query-method-based sorting is resolved entirely by Spring Data's method-name parser at startup, so a typo in the property name fails fast with a clear error.

Example: A repository method that needs to always return users ordered alphabetically by last name can simply be named findByOrderByLastNameAsc(), and Spring Data JPA generates the correct query automatically.

Code Example:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByOrderByLastNameAsc();

    List<User> findByStatusOrderByCreatedAtDesc(String status);
}

Interview Tip: A concise interview answer is:

"I can bake sorting straight into a derived query method name using OrderBy followed by the property and Asc or Desc, like findByOrderByLastNameAsc(). For sort order that needs to change at runtime based on user input, I'd instead accept a Sort or Pageable parameter rather than hardcoding it in the method name."