背景

处理数据库中的数据时有时需要保存json格式或者其他特殊格式,我们希望在保存数据时和取出数据时能自动完成这些数据的格式转换。如讲json转成对象或者简单的list结构,mybatis中的TypeHandler接口可以帮助我们实现。

解决

  1. 创建自定义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>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐