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].