views:

169

answers:

2

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??

A: 
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.

axtavt
Wowie! thanks! I searched all over and couldn't find it, this worked!
Zloy Smiertniy
A: 

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());
unsquared
Hey this is nice too, I may use it in the future.
Zloy Smiertniy