JPA Has a very neat option to query by example as explained here: Query by Example.
Is there any way to use this system to match to a timestamped object between two times?
For instance: I have logged sales in a database. I want to fetch all the sales of an item with ID: 7 between 07:00 and 13:00 on the 20th of October 2021.
In code terms, creating a query in the repository interface I would write:
@Query("SELECT s FROM Sale s "
+ "WHERE s.id IS ?1 "
+ "AND s.timestamp > ?2 "
+ "AND s.timestamp < ?3"
)
List<Sale> getSalesForIdBetweenTimestamps(
Long ID,
Timestamp after,
Timestamp before
);
...and then call it from the service, but using example matching I could just call it like so:
Example<Sale> saleExample = Example.of(new Sale().withID(7));
List<Sale> salesWithID = this.salesRepository.findAll(saleExample);
...which looks neater and doesn't require writing in the repository.
I know how to provide the example with the ID to find all sales of that item, and I could even create a custom matcher using this class to do before and after a single time. I can use a different solution by avoiding the entire "Query by Example" system, which is what I'm doing right now, but I would like to use it and can't figure out how to match between two times.