MyBatis自定义数据映射TypeHandler

假如想象 提交于 2019-12-10 03:43:35

在Mybatis的官方文档中说明了,框架内置的TypeHandler类型。请参见http://mybatis.github.io/mybatis-3/zh/configuration.html#typeHandlers

同时Mybatis支持自定义typeHandler。

例如:自定义了一个将Date存为毫秒时间的VARCHAR类型的TypeHandler


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了。

在resultMap的定义中对对应列定义typeHandler:


<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定义中添加相应的内容。如下:


<update id="updateRow" parameterType="Note">
    update note
    set update_time=#{updateTime, javaType=Date, jdbcType=VARCHAR}
    where id=#{id}
</update>


这样在update时,会将Date转换成毫秒时间。

在insert时,按照同样的处理方式即可。


在官方文档中看到其在update和insert的处理方式为

<update id="updateRow" parameterType="NoteBook">
    update note
    set update_time=#{updateTime,typeHandler=demo.CustomTimeStampHandler}
    where id=#{id}
</update>
但是我在测试时没有成功。







易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!