【问题标题】:how to show query while using query annotations with MongoRepository with spring data如何在使用带有 Spring 数据的 MongoRepository 的查询注释时显示查询
【发布时间】:2016-09-04 05:20:48
【问题描述】:

我在 Spring Boot 中使用 MongoRepository 来访问 mongo:

public interface MongoReadRepository extends MongoRepository<User, String> {
    @Query(value = "{$where: 'this.name == ?0'}", count = true)
    public Long countName(String name);
}

它可以工作,但我想知道它访问 mongo 的确切查询

怎么做?

我尝试在如下属性中添加一些配置:

logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
logging.level.org.springframework.data.mongodb.repository.Query=DEBUG

并且不工作。

有人可以帮忙吗?

【问题讨论】:

    标签: java spring mongodb spring-data mongorepository


    【解决方案1】:

    我在 application.properties 中添加了该行(如下)并且工作正常:

    logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
    

    查询:

    @Query("{$and: [{'$or' : [{ 'name': {$regex : ?0, $options: 'i'}}, {'description': {$regex : ?1, $options: 'i'}}]}, { 'deleted' : ?2 }]}")
    

    获取此日志:

    2016-09-27 10:53:26.245 DEBUG 13604 --- [nio-9090-exec-3] o.s.data.mongodb.core.MongoTemplate      : find using query: { "$and" : [ { "$or" : [ { "name" : { "$regex" : "c" , "$options" : "i"}} , { "description" : { "$regex" : "c" , "$options" : "i"}}]} , { "deleted" : false}]} fields: null for class: class com.habber.domain.Entity in collection: entities
    

    【讨论】:

    • 确保你已经导入了 log4j
    • 我什至导入了 log4j 并尝试了相同的解决方案,但它对我不起作用
    • 删除 .MongoTemplate。它作为 logging.level.org.springframework.data.mongodb.core
    【解决方案2】:

    另外,你可以使用一个 yml 配置文件,把它放在你的 application.yml 文件中。

    logging:
      level:
        org.springframework.data.mongodb.core.MongoTemplate: DEBUG
    

    【讨论】:

      【解决方案3】:

      对于 ReactiveMongo,将此属性添加到您的 .properties 文件中

      logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=DEBUG
      

      【讨论】:

        【解决方案4】:

        这是一个迟到的答案,但我发现根据问题尚未给出正确答案。

        人们已经给出的答案可能适用于其他场景。但是,如果您使用的是MongoRepository,那么正确的配置如下:

        logging.level.org.springframework.data.mongodb.repository.query= debug
        

        您在配置中使用 Query 而不是 query,这是错误的。

        当您添加正确的配置时,记录器将如下所示:

        25-06-2020 17:58:43.301 [http-nio-9001-exec-10] DEBUG o.s.d.m.r.query.MongoQueryCreator.complete(162) - Created query Query: { "customer.id" : 2}, Fields: {}, Sort: {}
        

        【讨论】:

          猜你喜欢
          • 2017-05-05
          • 2020-05-22
          • 2023-03-10
          • 1970-01-01
          • 2020-05-14
          • 2021-12-27
          • 2020-07-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多