Spring Data MongoDB:Spring Data Repository find方法的提示

ssm49v7z  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(76)

我正在实现Spring Data Repository,并让我的repository扩展MongoRepository。我正在寻找一种方法来指定我的findBy方法的提示,以便我可以控制。我见过几次非最佳索引被选为获胜计划。
这就是我的repository现在的样子:

public interface AccountRepository extends MongoRepository<Account, ObjectId> {

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

字符串
我研究了一堆,发现spring数据的JPARepository支持@QueryHint annotation,但我不相信MongoDb支持annotation。我可以在我的findBy方法上指定类似的annotation来指定hint吗?
MongoTemplate允许指定一个提示,但是,我有很多findBy方法,我不想在下面添加一个实现来指定一个提示。

2ledvvac

2ledvvac1#

从spring-data-mongo 4.1开始,您现在可以使用新的@Hint annotation为repository方法指定索引提示。
参考文档here
你的代码看起来像这样:

public interface AccountRepository extends MongoRepository<Account, ObjectId> {

  @Hint("my_custom_index_1")
  public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}

字符串
请注意,Mongo默认会自动选择一个合适的索引来执行存储库方法(就像它使用原生的mongosh .find(...)命令一样),所以只有当有特殊原因需要Mongo使用与它自动选择的索引不同的索引时,才应该使用@Hint注解。

相关问题