Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform date operations 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?

like image 224
amar4kintu Avatar asked Jun 24 '09 06:06

amar4kintu


People also ask

How to set date parameter in Hibernate Query?

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.


2 Answers

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')") );
like image 29
H2000 Avatar answered Sep 20 '22 14:09

H2000


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)"));
      }
    }
like image 147
Mark Bolusmjak Avatar answered Sep 18 '22 14:09

Mark Bolusmjak