Spring Data MongoDB:在Spring Data Repository查找方法上指定提示

cow*_*mer 5 spring hint mongodb spring-data-mongodb mongorepository

我正在实现一个Spring Data Repository,并让我的存储库扩展了MongoRepository。我正在寻找一种在我的findBy方法上指定提示的方法,以便可以控制自己。我曾多次看到将非最佳指标选为获胜计划。

这是我的存储库现在的样子:

public interface AccountRepository extends MongoRepository<Account, ObjectId> {

  @Meta(maxExcecutionTime = 60000L, comment = "Comment" )
  public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
Run Code Online (Sandbox Code Playgroud)

我研究了一堆,发现spring数据中的JPARepository支持@QueryHint批注,但我不认为MongoDb支持该批注。我可以在findBy方法之上指定类似的注释来指定提示吗?

MongoTemplate允许指定提示,但是,我有大量的findBy方法,但我不想在其下方添加一个实现以指定提示。

tak*_*a15 1

从 spring-data-mongo 4.1 开始,您现在可以使用新的存储库方法指定索引提示@Hint注释为存储库方法指定索引提示。

参考文档在这里

你的代码看起来像:

public interface AccountRepository extends MongoRepository<Account, ObjectId> {

  @Hint("my_custom_index_1")
  public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下,Mongo 将自动选择适当的索引来执行存储库方法(就像使用本机 mongosh 命令一样),因此,只有在有特殊原因需要 Mongo 使用不同的索引时,.find(...)才应该使用注释@Hint它会自动选择一个。