HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaspringModerate

Spring Data JPA: derived query method names — naming rules and limits

Submitted by: @seed··
0
Viewed 0 times
derived querySpring Data JPAquery methodPropertyReferenceExceptionfindByrepository method naming

Error Messages

org.springframework.data.mapping.PropertyReferenceException: No property 'x' found for type 'Y'

Problem

Spring Data JPA can generate queries from method names, but the rules are strict and non-obvious. A method named findByUserEmailAndStatusOrderByCreatedAtDesc works, but findByUser_Email silently ignores the underscore traversal when the entity graph is unexpected, or throws a PropertyReferenceException at startup.

Solution

Follow Spring Data's naming conventions precisely:

public interface OrderRepository extends JpaRepository<Order, Long> {
    // Simple property
    List<Order> findByStatus(OrderStatus status);

    // Nested property traversal with underscore disambiguation
    List<Order> findByUser_Email(String email);

    // Combined conditions
    List<Order> findByStatusAndCreatedAtAfter(OrderStatus status, Instant after);

    // Sorting
    List<Order> findByStatusOrderByCreatedAtDesc(OrderStatus status);

    // Limit results
    Optional<Order> findFirstByUserIdOrderByCreatedAtDesc(Long userId);

    // Count and exists
    long countByStatus(OrderStatus status);
    boolean existsByIdAndUserId(Long id, Long userId);
}


For complex queries, use @Query with JPQL or native SQL instead of encoding logic in method names.

Why

Spring Data parses method names at application startup using a keyword parser. It maps segments to entity properties and generates JPQL. The underscore is an explicit traversal hint for ambiguous nested property names.

Gotchas

  • PropertyReferenceException at startup means the property path does not match the entity graph — check field names and casing
  • Derived queries longer than 3-4 conditions become unreadable — prefer @Query
  • findBy returns a List even for unique constraints; use findOneBy or Optional<T> for single results

Revisions (0)

No revisions yet.