Leoncin
Leoncin

Reputation: 21

How to customize MongoRepository without overriding the annotated @Query methods in interface?

I want to customize MongoRepository by adding one method, and still using the implemented methods provided by MongoRepository. Below is the code:

public interface TopoRepositoryInterface extends MongoRepository<Topo, String>
{
    @Query("{'name':?0}")
    public Topo findByName(String name);

    public long getPublishedTopoCount();
}

the implementation declaration is:

public class TopoRepositoryImpl extends SimpleMongoRepository<Topo, String> implements TopoRepositoryInterface

If without the customization, method findByName declared in TopoRepositoryInterface can be automatically implemented by adding @Query("{'name':?0}") annotation. But now, since there is interface inheritage, I must add code

@Override
public Topo findByName(String name)
{
    Topo topo = getMongoOperations().findOne(Query.query(Criteria.where("name").is(name)), Topo.class);
    return topo;
}

Is there any way to write my own code for getPublishedTopoCount() only, and leave findByName() be implemented by @Query annotation? Thank you very much.

Upvotes: 2

Views: 13761

Answers (1)

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

You have to split your repository interface into two.

First one - "Custom" containing methods you implement manually would be:

public interface TopRepositoryCustom {
    long getPublishedTopoCount();
}

Second one for generated methods:

public interface TopRepository extends MongoRepository<Topo, String>, TopRepositoryCustom {
    @Query("{'name':?0}")
    Topo findByName(String name);  
}

Then you just need to implement first repository and remember to follow proper naming convention. See more at: spring-data mongodb custom implementation PropertyReferenceException and Spring Data MongoDB Custom implementations reference

Upvotes: 4

Related Questions