在Mybatis的官方文档中说明了,框架内置的TypeHandler类型。请参见http://mybatis.github.io/mybatis-3/zh/configuration.html#typeHandlers html
同时Mybatis支持自定义typeHandler。 java
例如:自定义了一个将Date存为毫秒时间的VARCHAR类型的TypeHandler git
package demo; public class CustomTimeStampHandler extends BaseTypeHandler<Date> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, String.valueOf(parameter.getTime())); } @Override public Date getNullableResult(ResultSet rs, String columnName) throws SQLException { String sqlTimestamp = rs.getString(columnName); if (sqlTimestamp != null) { return new Date(Long.parseLong(sqlTimestamp)); } return null; } @Override public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String sqlTimestamp = rs.getString(columnIndex); if (sqlTimestamp != null) { return new Date(Long.parseLong(sqlTimestamp)); } return null; } @Override public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String sqlTimestamp = cs.getString(columnIndex); if (sqlTimestamp != null) { return new Date(Long.parseLong(sqlTimestamp)); } return null; } }在Mybatis配置中注册该TypeHandler
<typeHandlers> <typeHandler handler="com.jd.jos.application.note.dao.CustomTimeStampHandler" javaType="java.util.Date" jdbcType="VARCHAR"/> </typeHandlers>
而后就在映射配置文件中使用该TypeHander了。 github
在resultMap的定义中对对应列定义typeHandler: sql
<resultMap type="Note" id="note-base"> <result property="id" column="id" /> <result property="updateTime" column="update_time" jdbcType="VARCHAR" javaType="Date" typeHandler="demo.CustomTimeStampHandler"/> </resultMap>
这里只能是在select的时候才会使用自定义的TypeHandler处理对应的映射关系,若是要在insert或者update时使用则须要在sql定义中添加相应的内容。以下: mybatis
<update id="updateRow" parameterType="Note"> update note set update_time=#{updateTime, javaType=Date, jdbcType=VARCHAR} where id=#{id} </update>
这样在update时,会将Date转换成毫秒时间。 app
在insert时,按照一样的处理方式便可。 框架
在官方文档中看到其在update和insert的处理方式为 ide
<update id="updateRow" parameterType="NoteBook"> update note set update_time=#{updateTime,typeHandler=demo.CustomTimeStampHandler} where id=#{id} </update>可是我在测试时没有成功。