Nicolas Romero
Nicolas Romero

Reputation: 28

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?

Upvotes: 0

Views: 200

Answers (1)

Mosius
Mosius

Reputation: 1682

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);
}

Upvotes: 2

Related Questions