简体   繁体   中英

Why can't i compare java.util.Date to mysql dates?

i have a strange situation:

I'm using jpa/hibernate to get rows from a mySql DB table where a date column is greater or equal to a date i send in (stripped out irrelevant code):

SELECT sp.* FROM spaceproduct sp where sp.enddate is null or sp.enddate >= :endDate)

in my code i basically do:

q.setParameter("endDate", new java.util.Date());

Now, my problem is when the date in the DB is the same date. ie "today", it doesn't get picked up. I assume that it's because it somehow also compares the time portion of the java.util.date to what's in the database (db value is "2011-10-28' only but the java.util Date is 2011-10-28T13:36:43.130+0200)

However, if i change the date parameter i set into a java.sql.Date(), it works!

Now, given that my mySql DB column is a Date, and not a DateTime, isnt this a bug? Even if i send in a java.util.date, shouldn't it only compare the date part since my DB column is a date?

EDIT: i tried using a util-date and convert it into a sql-date. That actually doesn't work either:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
q.setParameter("endDate", sqlDate);

So from what i can see, i have to set the time part to 0 also for sql-dates, unless i use the deprecated "year-month-date" constructor...

You can use System.currentTimeMillis() rather than creating a util Date to get that long. I would expect your edited code to work however, but if it doesn't you have no option but to discard the hours/minutes/seconds/milliseconds in some way such as doing System.currentTimeMillis() % 24 * 60 * 60 * 1000 (of course better to store that in a constant, but it gets the point across). Or you could just use Joda.

You should use java.sql.Date, as that is purely a date and does not contain time information. The reason it works with java.util.Date is that either the database or the JDBC driver does a widening conversion of the column from DATE to TIMESTAMP (with 00:00:00 time part) to make the comparison work with the parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM