可以自定义一些TypeHandler来对一些字段进行特殊处理,例如将一个varchar字段转成一个JAVABean中的String数组。将JavaBean中的long转成Timestamp等。
需要注意的:
1. JavaBean中的成员类型只能是类,如果是基本类型的要改成对应的包装类。
2. 配置文件中,如果是insert、update类型的语句,需要在字段中定义类型或者typehandler。查询的结果如果是定义了ResultMap,可以在对应的列定义中定义typehandler。
3. TypeHandler对应的类型可以在xml中定义,也可以在代码中通过注解@MappedTypes和@MappedJdbcTypes来定义
一个Long和Timestamp互转的例子:
@MappedTypes(Long.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class TimestampTypeHandler extends BaseTypeHandler<Long>{
@Override
public Long getNullableResult(ResultSet rs, String columnName)
throws SQLException {
Timestamp value = rs.getTimestamp(columnName);
if(value != null)
return value.getTime();
return 0l;
}
@Override
public Long getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp value = rs.getTimestamp(columnIndex);
if(value != null)
return value.getTime();
return 0l;
}
@Override
public Long getNullableResult(CallableStatement stmt, int parameterIndex)
throws SQLException {
Timestamp value = stmt.getTimestamp(parameterIndex);
if(value != null)
return value.getTime();
return 0l;
}
@Override
public void setNonNullParameter(PreparedStatement stmt, int parameterIndex,
Long value, JdbcType jdbcType) throws SQLException {
stmt.setTimestamp(parameterIndex, new Timestamp(value));
}
}
配置文件例子:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--这块等于dao接口的实现 namespace必须和接口的类路径一样-->
<mapper namespace="example.dao.IVerifyCodeDAO">
<resultMap type="VerifyCode" id="verifycodeMap">
<result column="phone" property="phonenum" />
<result property ="code" column="code" />
<result property="timestamp" column="timestamp" typeHandler="example.dao.typehandler.TimestampTypeHandler" />
</resultMap>
<insert id="insertVerifyCode1" parameterType="VerifyCode">
insert into T_VerifyCode
(phone,code,timestamp)
values(#{phonenum},#{code},#{timestamp,typeHandler=example.dao.typehandler.TimestampTypeHandler})
</insert>
<insert id="insertVerifyCode" parameterType="VerifyCode">
insert into T_VerifyCode
(phone,code,timestamp)
values(#{phonenum},#{code},#{timestamp,jdbcType=TIMESTAMP,javaType=java.lang.Long})
</insert>
<delete id="removeVerifyCode" parameterType="HashMap">
delete from T_VerifyCode where phone=#{phone}
</delete>
<select id="loadValidCodes" resultMap="verifycodeMap">
select phone,code,timestamp from T_VerifyCode
</select>
</mapper>