liveBook · Manning

Sorting algorithm

As explained in Java Persistence with Spring Data and Hibernate epub

Sorting is the ordering of query results according to one or more attributes.

Sorting orders repository query results by one or more attributes. Spring Data query methods express ordering in their names, while Sort and PageRequest supply runtime criteria for limited results and pages. section 15.2.2 section 17.3.2

Use these repository patterns to combine ordering with result limits or pagination:

  • Use findFirstByOrderByUsernameAsc() or findTopByOrderByRegistrationDateDesc() to retrieve one ordered result as Optional<User>. section 15.2.2
  • Pass Sort to methods such as findFirst2ByLevel(int level, Sort sort) or findByLevel(int level, Sort sort). section 17.3.2
  • Pass PageRequest through Pageable to specify page number, page size, and sorting criteria; return results as Page<User>. section 15.2.2

Repository sorting and paging

Optional<User> first = userRepository.findFirstByOrderByUsernameAsc(); Optional<User> newest = userRepository.findTopByOrderByRegistrationDateDesc(); Page<User> page = userRepository.findAll(PageRequest.of(1, 3)); List<User> users = userRepository.findFirst2ByLevel(2, Sort.by("registrationDate")); The first query orders by username ascending, the second by registration date descending, and the final queries combine limits or pages with a sort criterion.

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Defines derived method names, Sort, Pageable, and PageRequest usage, but does not detail generated query internals.
Examples
Uses username and registration-date ordering, level-filtered users, Sort.by, PageRequest.of, Optional<User>, and Page<User>.
What it assumes
Assumes repository query methods and teaches Sort, Pageable, and PageRequest for result ordering and pagination.
What you can do after
Apply it via Spring Data repository methods to retrieve ordered, limited, or paginated users.
How it connects
Connects query methods with query builders, pagination, Pageable, PageRequest, Sort, Spring Data JDBC, and Spring Data MongoDB.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.