I’m using Hibernate through JPA and I need to filter records by the time portion of their Date property .
public class Foo {
Date getDateTime() {
// Returns a date and time value.
}
}
Time startTime = ...;
Time endTime = ...;
TypedQuery<Foo> query = entityManager.createQuery("SELECT foo FROM Foo foo where :startTime <= foo.dateTime AND foo.dateTime <= :endTime", Foo.class);
query.setParameter("startTime", startTime);
query.setParameter("endTime ", endTime);
Of course this will not work because you can’t directly compare a Date and a Time. If this were a SQL query, then I would use a few DBMS-specific date functions to compare them, but how do you compare a Date and a Time in JPA?
Why not use a Native Query and then leverage the database specific functions you are familiar with. Once you have the Native Query you could convert the
java.sql.Timeobjects to longs and execute it.EntityManager API Documentation
For example if you were using Oracle.
The actual query will vary depending on your database flavor, however creating a NativeQuery should allow you to leverage the underlying vendor functions specific to your database.
Another way to approach this challenge would be to create a view that includes a column containing the time portion of the column with the date datatype. This would allow you to leverage the underlying database technology in a manner that is transparent in the code. Once this column is setup, you would establish the proper where clause in your Query.