Hibernate Query to fetch records on date ignoring timestamp

12,834
String hql = "from POJO as POJO where to_date(to_char(POJO.tradeDate, 'DD-MON-YY'), 'DD-MON-YY') = :date"; 
Query query = getSession().createQuery(hql); 
query.setParameter("date", date); 

[Edit]

Beware, the index, if there is any, on tradeDate will not be used if you follow the above query. In case, there are some performance concerns, you can rather do it like this,

String hql = "from POJO as POJO where POJO.tradeDate between :date and :ceilDate"; 
Query query = getSession().createQuery(hql); 
// a date having timestamp part, 00:00:00.0, or missing completely
query.setParameter("date", date); 
// a date having timestamp part, 23:59:59.999
query.setParameter("ceilDate", ceilDate); 
Share:
12,834
Arun
Author by

Arun

Updated on June 05, 2022

Comments

  • Arun
    Arun almost 2 years

    I have a timestamp column tradedate in one of the DB(Oracle) tables. I am using hibernate as the persistence layer to fetch and store Data to DB. I have a requirement in which I need to query the DB on date. i.e From UI the user passes a date and I need to get the filtered data based on this date.

    If the tradedate column only has the date part my query returns the correct records The issue arises when the tradedate column is populated with a timestamp value ie(date + time). Then those values are not returned by the query.

    eg:say there are 10 records for 23rd Oct 2010 in DB 5 of them have the timestamp entries and 5 dont

    So the query which i have returns me only the 5 rows which dont have timestamp.

    Now i know that i need to extract date from the timestamp and then do the comparision so that i get all the records for aprticular date but i dont know how its done with Hibernate and using HQL

    the query in Java/Hibernate that i am using is as follows

    String hql = "select Clearing from POJO as POJO where POJO.tradeDate = :date"; Query query = getSession().createQuery(hql); query.setParameter("date", date);