Disclaimer: this is needed for an old and ugly codebase that I'd much rather not touch.
- There is a table in the database that has a column (among many others) of
DATE
type. - There is a query (auto generated by Torque criteria - don't ask) with
java.util.Date
parameter; Torque formats it as full datetime.
So, the query MySQL is getting is something like:
SELECT * FROM my_table
WHERE my_date = '20091201105320'; // 2009-12-01 10:53:20
The problem is that on one server which has MySQL 5.0.27-standard it works just fine - as in returns all the records from my_table
that have my_date
set to '2009-12-01'. On another server which has MySQL 5.0.45 it does not work. The data is there - if I manually r开发者_运维百科un the query after trimming the time portion out I get correct results back.
The question is:
Is there a setting somewhere, either in MySQL configuration file or in per-session variables (connection string) or somewhere else to force MySQL to ignore the time portion during string constant to date conversion?
I obviously can't use DATE()
function without changing the codebase which I'd much rather not.
Apparently I'm out of luck. From MySQL manual:
Prior to MySQL 5.0.42, when DATE
values are compared with DATETIME
values, the time portion of the DATETIME
value is ignored, or the comparison could be performed as a string compare. Starting from MySQL
5.0.42, a DATE
value is coerced to the DATETIME
type by adding the time portion as '00:00:00'
.
Should anyone find themselves in a similar situation, the only workaround I found was to:
- Reset time fields (hours / minutes / seconds) of the
java.util.Date
instance to zero. - Patch (and I do mean "patch" - there is no way to plug in your own adapter)
getDateString()
method of Torque's DB adapter for MySQL (org.apache.torque.adapter.DBMM
) to check whether time fields of a date are zeroes and, if so, use "date-only" format.
This is simpler than patching Torque
Criteria cr = new Criteria();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String fixedDate = dateFormat.format(date);
cr.add("my_date", (Object)("my_date = '" + fixedDate + "'"), Criteria.CUSTOM);
精彩评论