5

I need to select some entities using HQL filtering by time. But I need to compare only date component without time. For example 1.1.2011 12.00 and 1.1.2011 13.20 must be equal.

What operator can I use?

@Query("FROM Item item " +
  "WHERE item.date [equality by date operator] :date " )
List<Item> findByDate(@Param("date") Date date);

3 Answers 3

13

If you do not mind DB-specific functions, you'd be able to do this (using Oracle as an example).

@Query("FROM Item item WHERE trunc(item.date) = trunc(:date) " )
List<Item> findByDate(@Param("date") Date date);

You can use this because the OracleDialect registers trunc as a StandardSQLFunction and Oracle's TRUNC removes the time component of a date.

1
  • 1
    In Oracle to avoid errors you can call trunc(item.date,'YYYY') to avoid some errors. Nov 10, 2015 at 18:54
10

If you do mind the DB-specific functions (and you should) then work with 2 dates:

  1. from date = date with time set to midnight
  2. to date = date with time set to 23:59:59.999

then query for dates >= from date and <= to date

2
  • I am using oracle db and its better for me to use trunc. Tnx for our answer
    – hatesms
    Nov 17, 2011 at 12:33
  • 3
    Fine but if you want to unit test with an in-memory DB where this is not supported you will be stuck. Nov 17, 2011 at 12:35
-2
"Select col from Table t where t.date = CURRENT_DATE()"

try this .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.