Video in progress

Junior 🌱 Spring

How do you write a derived query (a query from the method name), and when does it become awkward?

The name is built from findBy + field names + conditions (And, Or, Between, OrderBy...). When the conditions pile up and the name gets long, it's better to switch to @Query or a Specification.

📖 Answer

List<User> findByEmail(String email);
Optional<User> findFirstByPhoneOrderByCreatedAtDesc(String phone);
List<Order> findByStatusAndCreatedAtBetween(Status s, Instant from, Instant to);
long countByActiveTrue();
boolean existsByEmailIgnoreCase(String email);

Spring Data splits the name into pieces: findBy is the query type, Status and CreatedAt are entity fields, Between and IgnoreCase are conditions.

When does it get awkward? When it looks like this:

findByStatusAndCityAndCreatedAtAfterAndTotalGreaterThanOrderByCreatedAtDesc(...)

That's hard both to read and to change. If you need a specific query — @Query("select o from Order o where ..."). If the filters change depending on the user — a Specification or Querydsl.

One more thing: don't call methods that return a list from a big table without paging — add a Pageable. That's where the production cases come from where the whole table gets pulled into memory and the application slows down.