Video in progress

When are Spring Data's derived query methods (`findByStatusAndCreatedAtAfter`) convenient, and when is it better to write `@Query`?

For simple searches with two or three conditions, a derived method is convenient and is validated at startup. When the name gets long, or you need a join fetch, a projection or a complex condition, @Query (JPQL) or a Specification is easier to read and manage.

📖 Answer

Spring Data parses the method name and builds the JPQL:

List<Order> findByStatusAndCreatedAtAfter(Status status, Instant from);
Optional<User> findByEmailIgnoreCase(String email);
boolean existsByEmail(String email);
long countByStatus(Status status);

These are good: short, a wrong name fails right at startup (No property 'statsu' found), and they're easy to test.

The trouble starts when the name grows:

List<Order> findTop10ByCustomerRegionCodeAndStatusInAndTotalGreaterThanOrderByCreatedAtDesc(...);

Nobody reads that, and a mistake won't be visible in code review. Also, derived methods can't do a fetch join: if you need one, you add @EntityGraph. And deleteBy... first loads the entities and then deletes them one by one.

In that situation I write @Query:

@Query("""
       select o from Order o
       join fetch o.customer c
       where c.region.code = :region and o.status in :statuses
       order by o.createdAt desc""")
List<Order> findRecentByRegion(String region, Set<Status> statuses, Limit limit);

The Limit parameter has been available since Spring Data 3.2. In Spring Boot 3, if you compile with the -parameters flag, you don't have to write @Param.

If the filters are optional (a search form), neither fits: you need a Specification or the Criteria API there.