赞
踩
自定义了一 个将Date存为毫秒时间的VARCHAR类型的TypeHandler
1)新建类型转换类,实现TypeHandler接口,接口的泛型指定参数类型 ,重写了setNonNullParameter,getNullableResult方法。
public class CustomerTimeHandler 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;
}
}
2)在Mybatis 的主配置文件中注册上述定义的类型转换类
其中jdbcType可以指定的类型在Mybatis的枚举类org.apache.ibatis.type.JdbcType中有明确的定义,不能为该 枚举以外的值,
不然会出错。如果没有我们需要的类型,可指定为UNDEFINED。(也可以不指定具体的类型,在使用时用typeHandler指定具
体的类即可):
<typeHandlers>
<typeHandler handler="×××.CustomerTimeHandler"
javaType="java.util.Date" jdbcType="VARCHAR"/>
</typeHandlers>
3)在mapper映射文件中使用自定义的类型转换器
a) 在 resultMap的定义中对对应列定义typeHandler:
<resultMap type="Note" id="note-base">
<span></span><result property="id" column="id" />
<result property="customerTime" column="customer_time" jdbcType="VARCHAR" javaType="Date"
typeHandler=""×××.CustomerTimeHandler"/>
</resultMap>
b) 在 update使用则需要在sql定义中添加相应的内容
<update id="updateTime" parameterType="String">
update customer
set update_time=#{customerTime, javaType=java.Date, jdbcType=VARCHAR}
where id=#{id}
</update>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。