How to perform date operations in hibernate

前端 未结 8 1054
既然无缘
既然无缘 2020-12-10 03:00

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

相关标签:
8条回答
  • 2020-12-10 03:26

    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')") );
    
    0 讨论(0)
  • 2020-12-10 03:35

    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.

    0 讨论(0)
  • 2020-12-10 03:39

    Postgres users...

    registerFunction("dateadd", new SQLFunctionTemplate(StandardBasicTypes.DATE, "(?1 + INTERVAL ?2)"));
    

    with SQL usage like:

    now() < dateadd(:mydate, '-1 day')
    
    0 讨论(0)
  • 2020-12-10 03:40

    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.

    FROM_UNIXTIME(UNIX_TIMESTAMP(date)+ (allowedTimeWindow*86400)) as deadline
    

    It has limitations but it's a lot easier than the approaches above.

    0 讨论(0)
  • 2020-12-10 03:41

    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)"));
          }
        }
    
    0 讨论(0)
  • 2020-12-10 03:41

    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:

    current_timestamp() , current_date() , current_time()
    

    Arithmetic operations can be managed by:

    SECOND(...) , MINUTE(...) , HOUR(...) , DAY(...) , MONTH(...) , YEAR(...)
    
    0 讨论(0)
提交回复
热议问题