MyBatis自定义数据映射TypeHandler

从网上看到的帖子,感觉内容非常好,拷过来的(不愿意转载,不然被作者删除了,这么好的帖子就看不到了)。

原文:http://my.oschina.net/amoshuang/blog/134199

在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">
    <span></span><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>

但是我在测试时没有成功。
参照了以上以及网上找到的资料,自己写了一个将Mysql Blob转成String的typHeadler,可以在我的博客园的文件中下载。
posted @ 2015-08-27 09:37  季樊  阅读(836)  评论(0编辑  收藏  举报