javaspring-bootspring-dataspring-mongodbspring-mongo

MongoRepository same methods with diferent @Query


Using spring data mongo repository class, how can I do this? I need the same method twice but in one I need to exclude a field.

public interface Person extends MongoRepository<Person, String>{
        
    Optional<Person> findById(String id);

    @Query(fields="{ 'company': 0 }")
    Optional<Person> findById(String id);
}

This doesn't work because I can't have the same method twice, is there a way to do it?


Solution

  • The problem arises when you want to call the method. It would be ambiguous which method is being called.

    If you want to use method overloading to have a same name for both of your methods, it is only possible if they have different parameters.

    here is an example:

    public interface Person extends MongoRepository<Person, String>{
            
        Optional<Person> findById(String id);
    
        @Query(fields="{ 'company': 0 }")
        Optional<Person> findById(String id, Boolean exclude);
    }