在mybatis中插入查询自动格式化字段(TypeHandler)

背景

处理数据库中的数据时有时需要保存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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值