HQL make query searching by date (Java+NetBeans)

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

Hi all I have the following issue. I have a table of reserves in my MySQL DB, the date columns is defined DATETIME. I need to make a query using hibernate to find all reserves in one day no matter the hour, just that its the same year month and date, and I'm doing this

public List<Reserve> bringAllResByDate(Date date){  em = emf.createEntityManager(); Query q = em.createQuery("SELECT r FROM Reserve r WHERE r.date=:date "); q.setParameter("date", date); 

...

I really dont know how to make it compare, and bring me just those from the specified date, any help??

回答1:

I wish there were a database-agnostic way of casting datetimes as dates. This is usually how I deal with your scenario.

Calendar from = Calendar.getInstance(); Calendar to = Calendar.getInstance();  from.add(Calendar.DATE, -1); to.add(Calendar.DATE, 1);  Query q = em.createQuery("SELECT r FROM Reserve r WHERE r.date > :dateFrom AND r.date < :dateTo "); q.setParameter("dateFrom", from.getTimeInMillis()); q.setParameter("dateTo", to.getTimeInMillis()); 


回答2:

Query q = em.createQuery(     "SELECT r FROM Reserve r WHERE cast(r.date as date) = :date");  

Note that underlying database must support ANSI cast(... as ...) syntax.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!