Performing Date/Time Math In HQL?

前端 未结 4 1820
粉色の甜心
粉色の甜心 2020-11-27 06:53

I\'m looking how to perform date/time math within an HQL query. Specifically, how do I add or subtract (x) amount of time from the result of the current_timestamp()

相关标签:
4条回答
  • 2020-11-27 07:27

    Why do you need to do it in the query? Why not just handle it in the java code.

    for example:

    From RandomThing
    Where randomTime is not null and
          randomTime >= :currentTimestamp and
          randomTime <= :maxTimestamp
    

    And then just set the parameters.

    0 讨论(0)
  • 2020-11-27 07:29

    If you need the database server's time, you could first do a simple hql query to get the timestamp and then calculate the maxTimestamp in java and pass the fetched timestamp and the calculated maxTimeStamp to a query like the one of ccclark.

    0 讨论(0)
  • 2020-11-27 07:45

    You could determine the syntax to do it using SQL in your database and then define a function within a custom HibernateDialect. For example, we needed a weekday function which is not standard SQL. We subclassed the dialect for each database and then added a line like this:

    registerFunction("weekday", 
      new SQLFunctionTemplate(Hibernate.INTEGER, "to_char(?1,'D')") );
    

    In your case, you could use a function called date_diff which might be defined as ? - ? in some databases or something different in others. That way you don't have to write raw SQL in your query and if you ever need to switch databases, you just map the function differently in your dialect.

    0 讨论(0)
  • 2020-11-27 07:46

    Does it have to be HQL? I would probably switch up to a hibernate criteria and use:

    Criteria.add( Restrictions.SQLRestriction( "{alias} <= current_timestamp() " ) )
    Criteria.add( Restrictions.SQLRestriction( "{alias} >= (current_timestamp() + ?) ", 5 )
    
    0 讨论(0)
提交回复
热议问题