NO.79 JSONObject.fromBean java.sql.Date.getHours IllegalArgumentException问题之解决

--最终解决:将VO中所有 @Temporal(TemporalType.DATE)全部替换为 @Temporal(TemporalType.TIMESTAMP)

【现象】

近期某功能需要将一整个VO转化成JSON串,报出以下错误

2012-4-12 11:35:58 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet default threw exception
java.lang.IllegalArgumentException
at java.sql.Date.getHours(UnkNown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(UnkNown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(UnkNown Source)
at java.lang.reflect.Method.invoke(UnkNown Source)
at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2170)
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1332)
at org.apache.commons.beanutils.PropertyUtilsBean.getnestedProperty(PropertyUtilsBean.java:770)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:846)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:426)
at net.sf.json.JSONObject.fromBean(JSONObject.java:199)

【初步研究】

1.此VO中某日期字段实际上是java.util.Date类型的;

2.又看了一下java.sql.Date extends java.util.Date 中的 getHours方法

   /**
    * This method is deprecated and should not be used because sql Date 
    * values do not have a time component.
    *
    * @deprecated
    * @exception java.lang.IllegalArgumentException if this method is invoked
    * @see #setHours
    */
    public int getHours() {
	throw new java.lang.IllegalArgumentException();
    }


3.上网查,Hibernate jpa注释@Temporal(TemporalType.DATE)会将此列映射为java.sql.Date

/** 
* Type used to indicate a specific mapping of <code>java.util.Date</code> 
* or <code>java.util.Calendar</code>. 
* 
* @since Java Persistence 1.0 
*/ 
public enum TemporalType { 
/** 
* Map as <code>java.sql.Date</code> 
*/ 
DATE,/** 
* Map as <code>java.sql.Time</code> 
*/ 
TIME,/** 
* Map as <code>java.sql.Timestamp</code> 
*/ 
TIMESTAMP 
} 


【中间弯路】

重写java.sql.Date ,把里面的会throw new java.lang.IllegalArgumentException();的set、get方法全部干掉——以前经常无奈重写底层包中的类,重写JDK里的类还是第一次干,结果也就第一次发现:这次并没像以往一样会优先选用自己重写的类,CLAsspATH=./;%CLAsspATH%也不行;(--求达人解释原因@_@)

【最终解决

将@Temporal(TemporalType.DATE)全部替换为@Temporal(TemporalType.TIMESTAMP),这样属性一个java.sql.TimeStamp型,它可没有重写getHours方法。另外考虑数据库是Informix,本来Date型就没时分秒的(非time),原VO中原始类型定义又是java.util.Date,因此初步认为没啥不良影响。(个人认为,即使是Oracle的Date,应该也是无影响的,如果year-to-day的,不用的它的时分秒就好了)。

目前实际应用中暂未发现不良反应。

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...