Skip to content

Add annotation to disable query derivation for custom repository methods #5032

@neo-julio-falbo

Description

@neo-julio-falbo

Problem Statement

Spring Data MongoDB currently lacks an elegant way to disable automatic query derivation for custom repository methods that contain query keywords (like By, And, Or, etc.) in their names. This leads to PropertyReferenceException errors when developers want to implement custom logic for methods whose names happen to contain these keywords.

Current Behavior

When implementing custom repository methods using the fragment pattern, Spring Data MongoDB attempts to derive queries from method names even when a custom implementation is provided. This causes runtime exceptions when the method name contains query keywords but refers to non-existent properties.

Example Code That Fails

// Custom repository fragment
public interface CustomSnsRepository {
    boolean checkIfExistsByArn(String arn);  // Contains "By" keyword
}

// Custom implementation
public class CustomSnsRepositoryImpl implements CustomSnsRepository {
    private final MongoTemplate mongoTemplate;
    
    public CustomSnsRepositoryImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    
    @Override
    public boolean checkIfExistsByArn(String arn) {
        Query query = new Query(Criteria.where("arn").is(arn));
        return mongoTemplate.exists(query, SnsTopicEntity.class);
    }
}

// Main repository
@Repository
public interface SnsTopicRepository extends MongoRepository<SnsTopicEntity, String>, CustomSnsRepository {
}

Error produced:

Caused by: org.springframework.data.mapping.PropertyReferenceException: 
No property 'checkIfExistsByArn' found for type 'SnsTopicEntity'

Benefits

  1. Clear Intent: Explicitly indicates custom implementation is provided
  2. Natural Naming: Allows descriptive method names with query keywords
  3. Self-Documenting: Makes code intent obvious to other developers
  4. Backward Compatible: Doesn't affect existing functionality
  5. Consistent: Follows Spring's annotation-driven approach
  6. Maintainable: No complex configuration required

Environment

  • Spring Boot: 3.4.5
  • Spring Data MongoDB: Latest
  • Java: 17+

This feature would significantly improve the developer experience when working with custom repository implementations in Spring Data MongoDB by providing a clean, annotation-based solution that aligns with Spring Framework's design principles.

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions