如何自定义 MongoRepository 而不覆盖接口中带注释的 @Query 方法? [英] How to customize MongoRepository without overriding the annotated @Query methods in interface?

查看:449
本文介绍了如何自定义 MongoRepository 而不覆盖接口中带注释的 @Query 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过添加一个方法来自定义 MongoRepository,并且仍然使用 MongoRepository 提供的实现方法.代码如下:

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

实现声明是:

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

如果没有自定义,可以通过添加@Query("{'name':?0}")注解自动实现TopoRepositoryInterface中声明的findByName方法.但是现在,既然有接口继承,就必须加代码

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

有没有办法只为 getPublishedTopoCount() 编写自己的代码,而让 findByName() 由 @Query 注释实现?非常感谢你.

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

推荐答案

您必须将存储库界面拆分为两个.

You have to split your repository interface into two.

第一个 - 自定义"包含您手动实现的方法:

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

public interface TopRepositoryCustom {
    long getPublishedTopoCount();
}

生成方法的第二个:

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

然后你只需要实现第一个存储库并记住遵循正确的命名约定.查看更多信息:spring-data mongodb 自定义实现 PropertyReferenceExceptionSpring Data MongoDB 自定义实现参考

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

这篇关于如何自定义 MongoRepository 而不覆盖接口中带注释的 @Query 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆