I want to perform data time operations using hibernate HQL.
I want to add and subtract two dates as well as I want to subtract 1 year or 1 month from a particular date.
How is this possible using HQL in hibernate?
I want to perform data time operations using hibernate HQL.
I want to add and subtract two dates as well as I want to subtract 1 year or 1 month from a particular date.
How is this possible using HQL in hibernate?
Postgres users...
with SQL usage like:
See Performing Date/Time Math In HQL? for an example.
To use custom sql you must wrote an own hibernate dialect and register:
Disclaimer: I am a Java novice
I was able to use
current_date() >= fromDate AND dateadd(day, -1, getdate()) <= toDate
in an HQL statement against a Sybase db in Hibernate 3.5.3, without registering any functions.Usage sample of approach with dialect for JPA + Hibernate 4.3.1 + MySQL 5
public class SampleMySQL5InnoDBDialect extends org.hibernate.dialect.MySQL5InnoDBDialect {
then for your class with mapping annotation:
SampleEntity has toDate field of type java.sql.Date and duration integer field (duration in days) and we are calculating fromDate = toDate - duration and selecting all entities which have fromDate or toDate inside interval [startDate, endDate].
In Hibernate/MySQL (at least) You can convert to and from a Unix Timestamp. Since the unix timestamp is an integer you can add an integer number of seconds to it.
It has limitations but it's a lot easier than the approaches above.
This is an open issue in Hibernate. As of Hibernate 3.3 there is no standard way to handle date comparisons purely in HQL:
https://hibernate.atlassian.net/browse/HHH-2434
Hibernate 4.3 offers functions to access Date/Time in HQL which are:
Arithmetic operations can be managed by: