背景
处理数据库中的数据时有时需要保存json格式或者其他特殊格式,我们希望在保存数据时和取出数据时能自动完成这些数据的格式转换。如讲json转成对象或者简单的list结构,mybatis中的TypeHandler接口可以帮助我们实现。
解决
创建自定义TypeHandler
因为mybatis默认实现的TypeHandler可能不满足我们的需求,所以需要我们自己实现符合业务需求的TypeHandler。
继承BaseTypeHandler类
BaseTypeHandler类为我们实现了一些TypeHandler基础功能,继承这个类可以简化我们实现TypeHandler接口的操作
public class JsonArrayTypeHandler extends BaseTypeHandler<Object> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, JSONUtil.toJsonStr(parameter));
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
String string = rs.getString(columnName);
if (StrUtil.isBlank(string)) {
return null;
}
return JSONUtil.parseArray(string);
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String string = rs.getString(columnIndex);
if (StrUtil.isBlank(string)) {
return null;
}
return JSONUtil.parseArray(string);
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String string = cs.getString(columnIndex);
if (StrUtil.isBlank(string)) {
return null;
}
return JSONUtil.parseArray(string);
}
}
2.使用自定义的TypeHandler
创建时使用指定的TypeHandler
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into wo_post(`title`, summary, `publish_time`, content, tags, update_time) value
(#{title}, #{summary}, #{publishTime}, #{content}, #{tags, jdbcType=VARCHAR, typeHandler=com.mh.stage.common.mybatis.handler.JsonArrayTypeHandler}, #{updateTime})
</insert>
查询时使用指定的TypeHandler
查询时要通过resultMap的方式定义返回的结果集
<resultMap id="postMap" type="PostDao">
<id property="id" column="id"/>
<result property="title" column="title"/>
<result property="summary" column="summary"/>
<result property="publishTime" column="publish_time"/>
<result property="updateTime" column="update_time"/>
<result property="content" column="content"/>
<result property="tags" column="tags" jdbcType="VARCHAR" typeHandler="com.mh.stage.common.mybatis.handler.JsonArrayTypeHandler"/>
</resultMap>
<select id="get" resultMap="knowledgeMap">
select * from wo_post where id=#{id}
</select>