-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
Spring Data's query derivation is a powerful feature, but it enforces a strict coupling between the method name and the query logic.
As the query complexity grows (multiple parameters, ordering, filters), the method name often becomes excessively long and unreadable.
To avoid this, developers are forced to switch to @Query with JPQL. However, switching to JPQL means losing the convenience of the keyword-based syntax (like automatic property path resolution) and introducing raw query strings that are more verbose for simple predicates.
Proposal
I propose a mechanism to use the query derivation syntax inside an annotation, allowing developers to choose a clean, domain-specific name for the method itself.
This would allow us to keep the benefits of derived queries (conciseness, startup validation) without polluting the repository interface with implementation details.
Example
Current situation:
public interface UserRepository extends JpaRepository<User, Long> {
// Hard to read, exposes implementation details
List<User> findByLastnameIgnoreCaseAndActiveTrueAndEmailIsNotNullOrderByCreatedAtDesc(String lastname);
}Desired behavior:
public interface UserRepository extends JpaRepository<User, Long> {
// @DerivedQuery contains the keyword string
@DerivedQuery("findByLastnameIgnoreCaseAndActiveTrueAndEmailIsNotNullOrderByCreatedAtDesc")
List<User> findActiveUsers(String lastname);
}Benefits
- Readability: Repository interfaces remain clean, concise, and focused on business intent rather than database columns.
- Refactoring Safety: Changing the query criteria (e.g., adding a sort order or a status filter) does not require renaming the Java method, avoiding breaking changes for all the clients calling that method.
- Productivity: It retains the ease of use of the derivation parser (no need to write full
SELECTstatements for simple predicates) without the penalty of "ugly" method names.