Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing Date/Time Math In HQL?

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() function? Or do I have to drop into SQL for this and hope that whatever database is being run supports it?

HQL query example:

FROM RandomThing
WHERE randomTime IS NOT NULL AND
      randomTime >= current_timestamp() AND
      randomTime <= (current_timestamp() + :timeToAdd)

I can define the :timeToSubtract parameter to be any particular unit, though anything bigger than hours would be undesirable, and seconds would be most desirable.

CLARIFICATION: I realize this can be easily done outside of the query. But for philosophical reasons, let's say it's important to use the database server's time, rather than the querying system's time. Practical example: I'm querying an automatic timestamp for all entries made within the last (x) amount of time. Since the timestamp is made by the database system, it is important to also use the database's current time.

like image 594
jdmichal Avatar asked Mar 12 '09 16:03

jdmichal


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.

Which is faster SQL or HQL?

You can select only certain columns with HQL, too, for example you can use select column from table in HQL. Native SQL is not necessarily faster than HQL. HQL finally also is translated into SQL (you can see the generated statement when running the application with the show_sql property set to true).

What are the basic properties of HQL?

Features of HQLHQL supports polymorphism as well as associations, which in turn allows developers to write queries using less code as compared to SQL. In addition, HQL supports many other SQL statement and aggregate functions, such as sum() and max() and clauses, such as group by and order by.


1 Answers

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.

like image 80
ccclark Avatar answered Oct 05 '22 10:10

ccclark