开发者

Hibernate Query to fetch records on date ignoring timestamp

开发者 https://www.devze.com 2023-01-21 15:19 出处:网络
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 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 retur开发者_如何学Pythonns 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);


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); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号