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 da
Usage sample of approach with dialect for JPA + Hibernate 4.3.1 + MySQL 5
public class SampleMySQL5InnoDBDialect extends org.hibernate.dialect.MySQL5InnoDBDialect {
public SampleMySQL5InnoDBDialect() {
super();
registerFunction("date_sub_days", new SQLFunctionTemplate(StandardBasicTypes.DATE, "date_sub(?1, interval ?2 day)"));
}
then for your class with mapping annotation:
@NamedQuery(name = "SampleEntity.getSampleEntitiesForGapOverlapCalculations", query = "from SampleEntity as se where "
+ "((se.toDate between :startDate and :endDate) or (date_sub_days(se.toDate, se.duration) between :startDate and :endDate)) order by se.toDate asc, se.duration desc")
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].
Hibernate4.3 provides native functions to access Dates/Timestamps and to perform arithmatic operations on them
Here is the link to the documentation of what expressions can be used in HQL. Few of which i am mentioning: To access date/time:
current_date(), current_time(), and current_timestamp()
Arithmetic operations can be done by following. These functions take Time as input:
second(...), minute(...), hour(...), day(...), month(...), and year(...)
One can get absolute difference of in HQL by
current_timestamp() - dateInstance
where dateInstance can have definition
@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date updatedAt;
The result is in 0.1 seconds. So for a absolute difference of 1 second, the above expression will give result as 10.
So a query would look like :
select t from Table t where (current_timestamp() - updatedAt)>600