【问题标题】:how to call MongoTemplate function on Autowired instance of MongoTemplate in Spring boot如何在 Spring boot 中调用 MongoTemplate 的 Autowired 实例上的 MongoTemplate 函数
【发布时间】:2018-01-11 13:01:06
【问题描述】:

我已经在 Spring Boot 中配置了 MongoDB 连接。现在我想使用 MongoTemplate find() 方法运行自定义查询。但是弹簧靴不允许我这样做。

@Autowired
MongoTemplate mongoTemplate;

public List<UserVO> findByQuery(String query) {
    List<UserVO> users = mongoTemplate.find(query, UserVO.class);
    return users;
}

mongoTemplate 使用 mongo URI 自动配置,集合名称在 UserVO.class 中使用 @Document 定义。

错误:MongoOperations 类型中的方法 find(Query, Class) 不适用于参数 (String, Class)

任何建议都将受到高度赞赏。

【问题讨论】:

  • 正如错误消息中明确指出的那样,mongoTemplate.find(...) 采用 Query 对象和类。您正在传递一个字符串和类。您必须将 String 中的查询转换为 Query
  • 感谢您的指出。致力于创建 Query 对象。坚持使用条件在单个 OR 语句中添加多个 AND。
  • 把你试过的代码,以及你想用查询实现什么
  • 现在完成了。

标签: java mongodb spring-boot autowired mongotemplate


【解决方案1】:

按照规范 mongoTemplate.find(Query query, Class entityClass) 有这样的参数

您需要指定Query like

new Query(Criteria.where("fieldName").is("searchValue")

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2016-11-12
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2019-04-12
    • 2017-03-02
    相关资源
    最近更新 更多