关于Oracle字段类型Date使用mybatis generator自动生成工具出现的查询日期只精确到年月日问题
工作需要使用mybatis generator,另外Oracle和mybatis也没有做过深入的了解,只是能用会写业务代码,不报错就可以了。
废话,割------------------------------------------------------------------------------------------------------------------------------------
在使用Oracle+mybatis做sql查询时,发现查询出来的结果只精确到年月日,因为mybatis的orm映射由mybatis generator来做的,所以自己以为在哪个地方业务代码转换是出了错,Debug的时候才发现出错的是sql查询。
其中一点在网上找到了(http://www.soso.io/article/72293.html),文章中提到:
mybatis jdbcType: DATE ,TIMESTAMP 区别:
1. mybatis中 jdbcType 时间类型
当jdbcType = DATE 时, 只传入了 年月日
jdbcType = TIMESTAMP , 年月日+ 时分秒
2. jdbcType 是否必须:
使用时, 没有加jdbcType 正常,
加上jdbcType原因(网络): 当传入字段值为null,时,需要加入. 否则报错.
于是修改了,sqlMap中的所有jdbcType=DATE 为TIMESTAMP,保存编译运行结果还是精确到年月日。
翻开旧项目需要差异,发现因为Oracle中的字段类型是Date的缘故,mybatis generator自动生成了几个个addCriterionForJDBCDate方法,而所有对应Date类型的字段,都使用了该方法,代码如下:
1 protected void addCriterionForJDBCDate(String condition, Date value, String property) { 2 if (value == null) { 3 throw new RuntimeException("Value for " + property + " cannot be null"); 4 } 5 addCriterion(condition, new java.sql.Date(value.getTime()), property); 6 } 7 8 protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) { 9 if (values == null || values.size() == 0) { 10 throw new RuntimeException("Value list for " + property + " cannot be null or empty"); 11 } 12 List<java.sql.Date> dateList = new ArrayList<java.sql.Date>(); 13 Iterator<Date> iter = values.iterator(); 14 while (iter.hasNext()) { 15 dateList.add(new java.sql.Date(iter.next().getTime())); 16 } 17 addCriterion(condition, dateList, property); 18 } 19 20 protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { 21 if (value1 == null || value2 == null) { 22 throw new RuntimeException("Between values for " + property + " cannot be null"); 23 } 24 addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); 25 }
其中Java.sql.Date(value1.getTime())结果是精确到年月日,至于为什么,后续有时间补充。