【问题标题】:MongoRepository @Query Failed to parse string as a dateMongoRepository @Query 无法将字符串解析为日期
【发布时间】:2019-03-22 03:31:12
【问题描述】:

首先,我的问题是通过 Spring MongoDb 的 MongoRepository 在 MongoDB 中搜索集合。

我的对象:

{
    "_id" : ObjectId("5c78e1f447f39c2eacb229d7"),
    "lab" : "xxx",
    "type" : "Holiday",
    "description" : "Lunar New Year",
    "start_date" : ISODate("2019-02-04T02:37:42.152Z"),
    "end_date" : ISODate("2019-02-08T06:37:42.152Z"),
    "all_day" : true,
    "_class" : "xxx.Event"
}

我可以在 Mongo 查询中随心所欲地做:

db.getCollection('event').find({"start_date" : {$gte :ISODate( "2019-02-03T02:37:42.152Z") , $lte :ISODate( "2019-02-08T02:37:42.152Z")}})

(您可以将 ISODate 替换为新日期)

但要在 Spring 中进行,我想这样做:

@Query("   $or: [ {start_date : {$gte :ISODate( ?0 ) , $lte :ISODate( ?1)}} , {end_date : {$gte :ISODate( ?0) , $lte :ISODate( ?1)}} ]  }  ")
List<Event> findAllEventByTime(String from, String to);

但它失败了,我搜索了两个主题: herethere

最终得到

@Query("{ 'start_date' : {$gte : {'$date': '?0'}, $lte :{'$date': '?1'} }}")
List<Event> findAllEventByTime(String from, String to);

但我又遇到了解析问题:

2019-03-22 10:09:48.261 错误 9316 --- [XNIO-2 任务 1] o.z.problem.spring.common.AdviceTrait:内部服务器错误

org.bson.json.JsonParseException:无法将字符串解析为日期 org.bson.json.JsonReader.visitDateTimeExtendedJson(JsonReader.java:1057)

我尝试推荐:

尝试参数:Fri Mar 22 10:09:48 ICT 2019 和 2019-03-22T03:09:48.227Z 和 2016-04-14 00:00:00

所有这一切都在下降... 你们能帮我解决吗?

工作流程:来自 FE(字符串)的参数 ~> 转到 BE ~> 如上所述调用 Repo

【问题讨论】:

    标签: mongodb spring-data-mongodb mongorepository


    【解决方案1】:

    你可以像下面这样创建spring data jpa 方法:-

    List<Event>  findByStart_dateIsAfterAndEnd_dateIsBefore(Date startDate, Date endDate);
    

    【讨论】:

    • 我会尝试: List findAllBystartDate(Instant startdate);并得到:2019-03-22 11:22:15.059 ERROR 7740 --- [XNIO-2 task-3] o.z.problem.spring.common.AdviceTrait: Internal Server Error org.bson.codecs.configuration.CodecConfigurationException: Can' t 为类 java.time.ZonedDateTime 找到编解码器。
    • 感谢您的建议,我一路测试并最终使用 Srping Data JPA 的自动转换,但我们需要更改类型
    【解决方案2】:

    我用其他方法解决:

    1. 在存储库中
      • 我无法使用原始查询或任何需要从字符串转换为日期的查询进行转换
      • 使用 MongoRepository 的自动生成查询支持
    Page<Event> findAllByStartDateBetweenOrEndDateBetween(Instant fromDate1, Instant toDate1, Instant fromDate2, Instant toDate2, Pageable pageable);
        List<Event> findAllByStartDateBetweenOrEndDateBetween(Instant fromDate1, Instant toDate1, Instant fromDate2, Instant toDate2);
    
    1. 输入数据: 使用 Instant 或 LocalDate / LocalDateTime 并将其转换为 Instant ~> 然后在查询中用作参数(由 Spring 自动转换)
    @RequestParam Instant startDate, @RequestParam Instant endDate
    

    并使用:

    eventRepository.findAllByStartDateBetweenOrEndDateBetween(startDate, endDate, startDate, endDate))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      相关资源
      最近更新 更多