MongoRepository @Query Failed to parse string as a date

∥☆過路亽.° 提交于 2020-01-15 12:15:37

问题


First of all, my issue is searching Collecttions in MongoDB via Spring JPA (MongoRepository).

My Object:

{
    "_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"
}

i can do as my wish in Mongo query as:

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

(you can replace ISODate with new Date)

But to do it in Spring, i want to do it as:

@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);

But it fail, i searched in two topic: here and there

and end up with

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

But once again, i had the problem with parsing:

2019-03-22 10:09:48.261 ERROR 9316 --- [ XNIO-2 task-1] o.z.problem.spring.common.AdviceTrait : Internal Server Error

org.bson.json.JsonParseException: Failed to parse string as a date at org.bson.json.JsonReader.visitDateTimeExtendedJson(JsonReader.java:1057)

I try with recomment:

Try param: Fri Mar 22 10:09:48 ICT 2019 and 2019-03-22T03:09:48.227Z and 2016-04-14 00:00:00

All of this going down... Can you guys help me to fix it?

Work-Flow: Params from FE (String) ~> Go to BE ~> Call Repo as above


回答1:


You can make spring data jpa method for the same like below:-

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



回答2:


I resolve it with other method:

  1. In repository
    • I can't convert with raw query or any query that need to convert from String to Date
    • Use the auto generate query support by 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. Input Data: Use Instant or LocalDate / LocalDateTime and convert it to Instant ~> Then use as param in query (auto convert by Spring)
@RequestParam Instant startDate, @RequestParam Instant endDate

and use:

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


来源:https://stackoverflow.com/questions/55292497/mongorepository-query-failed-to-parse-string-as-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!