Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HQL to query on a date while ignoring the time on Oracle

I have a table (in Oracle 9 and up) where I need to find all entries for a given day using Hibernate. The entries have timestamps (with data type 'date'). Some of the entries have a time, others only have a date. This can not be changed, as this is the output of other applications which I can not change. In SQL I would write something along the lines of

SELECT * FROM table WHERE trim(table.date) = to_date('11.06.2009')

to get all entries for the date I am looking for. I was wondering how I can get Hibernate to do this using HQL. I know I can use SQL-queries in Hibernate, but this seems to be less clean. Is there a way to do this? If possible, this way should also work on non-oracle databases where timestamp would be the data type.

like image 887
Thomas Lötzer Avatar asked Jun 11 '09 10:06

Thomas Lötzer


People also ask

How do I pass a date in HQL query?

YEAR, -1); String dateLimit = cal. getTime(). toString(); Date dateFormatter = new SimpleDateFormat("dd-MMM-yyyy").

How do I compare dates in HQL?

In Oracle You Can Use HQL trunc() Date Function Another function you can use for HQL date comparison queries is the HQL trunc() function. This function discards the hour part of the date. Please note that this will only work when using Hibernate with Oracle and the OracleDialect .

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.


1 Answers

You could put two constraints into your HQL, one that specifies greater than or equal to the start of the date you are searching on, and one that specifies less than the next day.

i.e.

table.date >=11.06.2009 AND table.date < 11.07.2009

HQL (as well as SQL) also allows for:

table.date between 11.06.2009 AND 11.07.2009

Keep in mind between is always inclusive, meaning it's both >= and <= respectively.
More details on between here: http://www.coding-dude.com/wp/java/hibernate-java/hibernate-hql-between-expression/

like image 86
tschaible Avatar answered Oct 19 '22 10:10

tschaible