MyBatis自定义数据映射TypeHandler

在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>
但是我在测试时没有成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值