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?
As it turned out Hibernate doesn't convert dates to GMT automatically, it just cuts off time if you use query. setDate() , so if you pass "2009-01-16 12:13:14" it becomes "2009-01-16 00:00:00". To take time into consideration you need to use query. setTimestamp("date", dateObj) instead.
See Performing Date/Time Math In HQL? for an example.
To use custom sql you must wrote an own hibernate dialect and register:
registerFunction("weekday",
new SQLFunctionTemplate(Hibernate.INTEGER, "to_char(?1,'D')") );
You need to create your own dialect. Something like the following:
public class MyDialect extends MySQLInnoDBDialect{
public MyDialect() {
super();
registerFunction("date_add_interval", new SQLFunctionTemplate(Hibernate.DATE, "date_add(?1, INTERVAL ?2 ?3)"));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With