【问题标题】:Spring Data MongoDB. Custom @Query with current date弹簧数据 MongoDB。具有当前日期的自定义 @Query
【发布时间】:2016-09-30 14:14:07
【问题描述】:

我想查找过去 2 小时内的所有文档。

@Repository
public interface EventRepository extends MongoRepository<Event, Long> {

    @Query("{'createdAt': {$gt: new Date(ISODate().getTime() - 1000 * 60 * 60 * 2)}}")
    List<Event> findLive();

}

但是有一个错误:

09-30 14:06:33 WARN org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'actionController' defined in file [/Users/serge/projects/bb/bb-whlive/target/classes/bb/whlive/controller/ActionController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventService' defined in file [/Users/serge/projects/bb/bb-whlive/target/classes/bb/whlive/service/EventService.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eventRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
{'createdAt': {$gt: new Date(ISODate().getTime() - 1000 * 60 * 60 * 2)}}
                 ^

我知道如何通过 MongoTemplate 做到这一点。但是可以通过 MongoRepository 来实现吗?

附:在 mongo shell 中,此查询工作正常:

db.events.find({'createdAt': {$gt: new Date(ISODate().getTime() - 1000 * 60 * 60 * 2)}}).pretty();

【问题讨论】:

    标签: spring-data spring-data-mongodb


    【解决方案1】:

    代替

    @Query("{'createdAt': {$gt: new Date(ISODate().getTime() - 1000 * 60 * 60 * 2)}}")
    

    使用下面的一个

    @Query("{'createdAt': { $gt: ISODate().getTime() - 1000 * 60 * 60 * 2 }}")
    

    希望对你有帮助!!!

    【讨论】:

    • 它不起作用:原因:org.springframework.beans.factory.BeanCreationException:创建名为“data3Repository”的bean时出错:调用init方法失败;嵌套异常是 com.mongodb.util.JSONParseException: {'createdAt': { $gt: ISODate().getTime() - 1000 * 60 * 60 * 5 }} ^ at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory .initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 2020-01-04
    • 2013-10-15
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多