A query method retrieves data through a repository interface without a handwritten query. Spring Data derives its behavior from the method name: it recognizes a prefix such as find…By, get…By, read…By, query…By, or count…By, then parses the remaining property names and keywords. The declared return type also matters; Optional<User> requests an optional result. section 4.4 section 15.2.1
Finding users
For a User with username, email, level, and registrationDate properties, a repository can declare findByUsername(String username), findByRegistrationDateBetween(LocalDate start, LocalDate end), and findByUsernameAndEmail(String username, String email). Other supported names express case-insensitive matching, comparisons, and ordering: findByUsernameIgnoreCase(String username), findByLevelGreaterThanEqual(int level), and findAllByOrderByUsernameAsc(). Tests can save users, call these methods, and assert both the matches and their order. section 4.4 section 15.2.1
Listing 4.7 The UserRepository interface with new methods
Path: Ch04/springdatajpa2/src/main/java/com/manning/javapersistence /springdatajpa/repositories/UserRepository.java public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); List<User> findAllByOrderByUsernameAsc(); List<User> findByRegistrationDateBetween(LocalDate start, LocalDate end); List<User> findByUsernameAndEmail(String username, String email); List<User> findByUsernameOrEmail(String username, String email); List<User> findByUsernameIgnoreCase(String username); List<User> findByLevelOrderByUsernameDesc(int level); List<User> findByLevelGreaterThanEqual(int level); List<User> findByUsernameContaining(String text); List<User> findByUsernameLike(String text); List<User> findByUsernameStartingWith(String start); List<User> findByUsernameEndingWith(String end); List<User> findByActive(boolean active); List<User> findByRegistrationDateIn(Collection<LocalDate> dates); List<User> findByRegistrationDateNotIn(Collection<LocalDate> dates); }
The UserRepository listing groups derived methods for exact matches, ranges, combined conditions, text matching, and ordering. section 4.4
The convention spans Spring Data JPA, JDBC, and MongoDB, but the resulting queries target different stores. Spring Data JDBC has supported name-derived queries since version 2.0; its derived conditions can use properties in a WHERE clause, but not joins. In JDBC and MongoDB, a name that refers to a nonexistent entity property produces an error when the application context loads. section 4.4 section 15.2.1 section 17.3.1
Use @Query when the name alone cannot express the required lookup. For example, countByUserId follows the naming pattern but needs an explicit SQL query in a Spring Data JDBC repository because userId is not a property of UserAddress. Query methods are therefore a concise choice for supported property-based retrieval, not a replacement for every custom query. section 15.3.4 section 4.11
