可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.