3

Very similar to this question: Check date between two other dates spring data jpa

However, I am attempting to do this with MongoDB and java.time.LocalDateTime.

I have tried:

  • findAllByMetadataStartTimeBetween(start, end) (works, but exclusive start/end)
  • findAllByMetadataStartTimeGreaterThanEqual(start) (works, but no end)

However, when I try: findAllByMetadataStartTimeGreaterThanEqualAndMetadataStartTimeLessThanEqual(start,end)

I get the error: json can't serialize type : class java.time.LocalDateTime

Any idea why this particular combination throws this error, when the previous ones do not?

pennstatephil
  • 1,593
  • 3
  • 22
  • 43

3 Answers3

4

Try the below code. I am sure, works for inclusive

@Query("{'dateTime' : { $gte: ?0, $lte: ?1 } }")
List<YourObject> findByDateTimeBetween(Date from, Date to);

Spring data method signature below works for exclusive

public List<YourObject> findByDateBetween(Date from, Date to);
0

You have to make custom query:

Query query = new Query(
      new Criteria().andOperator(
    Criteria.where("metadataStartTime").gte(start),
    Criteria.where("metadataStartTime").lte(end)
  )
);

return mongoTemplate.find(query, EntityName.class);
salerokada
  • 334
  • 3
  • 7
0

JPA "Between" method is inclusive. The problem is probably with the precision of your Date Object.

Try to make sure The compared start date has the exact hours, minutes, seconds and milliseconds. Even if is the searched data is some milliseconds ahead it won't be caught by the query.

In my case, when I set them all for start date to 00:00:00.000, and for the end date to 23:59:59.999 The JPA findAllByMetadataStartTimeBetween(start, end) works fine and inclusive.

  • I would not say it is inclusive :) I even fetched `seconds` from `Instant` (so the query is like `findAllByTime_SecondsBetween(from, to)` and it still does not work as expected. With subtraction and addition of one second to the period, it does. – Witold Kupś Oct 12 '22 at 06:40