使用Mybatis的TypeHandler优雅的存取自定义对象

引言 接到一个需求,在原有的对象基础上,加了20多个新属性,对于这些数据仅仅只有查看的用途,所以打算在数据库新增一个base字段,存入这20多个新属性 按以往的做法,就是将20多个属性的新对象通过代码转成json字符串后保存,读取的时候将json转为对象返回前端,每次保存和查询都要类似操作 于是想到了Mybatis的TypeHandle,让自定义对象优雅的存取

这里提供2个方案实现: 方案1: 1、新建一个类,继承BaseTypeHandler

@MappedTypes(BaseInfo.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class BaseInfoTypeHandler extends org.apache.ibatis.type.BaseTypeHandler<BaseInfo> {
          
   

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, BaseInfo BaseInfo, JdbcType jdbcType) throws SQLException {
          
   
        preparedStatement.setString(i, JsonUtils.toJson(BaseInfo));
    }

    @Override
    public BaseInfo getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
          
   
        return JSON.parseObject(resultSet.getString(columnName), BaseInfo.class);
    }

    @Override
    public BaseInfo getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
          
   
        if(StringUtils.isEmpty(resultSet.getString(columnIndex))){
          
   
            return null;
        }
        return JSON.parseObject(resultSet.getString(columnIndex), BaseInfo.class);

    }

    @Override
    public BaseInfo getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
          
   
        if(StringUtils.isEmpty(callableStatement.getString(columnIndex))){
          
   
            return null;
        }
        return JSON.parseObject(callableStatement.getString(columnIndex), BaseInfo.class);
    }

2、在数据库的PO对象上和对应的数据库字段上,加上注解,设置autoResultMap=true

//数据库PO类上
@TableName(value = "test_one", autoResultMap = true)
//PO类中对应的对象字段
@TableField(value = "base_info", typeHandler = BaseInfoTypeHandler .class)
    private BaseInfo baseInfo;

3、在对应的mapper.xml中配置属性

<resultMap id="BaseResultMap" type="com.***.po.XXXBasePO">
        <id column="id" jdbcType="BIGINT" property="id" />
			...
			...
        <result column="base_info" jdbcType="VARCHAR" property="baseInfo" typeHandler="com.****.BaseInfoTypeHandler"/>
    </resultMap>

4、在注册中心配置mybatisplus的配置,路径是你新建的BaseInfoTypeHandler的路径,用于启动扫描该类,实现对象的转换 type-handlers-package: com.*

方案2: 利用Mybatisplus自带的FastjsonTypeHandler实现 1、在数据库的PO对象上和对应的数据库字段上,加上注解,设置autoResultMap=true

//数据库PO类上
@TableName(value = "test_one", autoResultMap = true)
//PO类中对应的对象字段
@TableField(value = "base_info", typeHandler = FastjsonTypeHandler.class)
    private BaseInfo baseInfo;

2、如果是手写的XML,切记一定要用resultMap,不可用resultType,否则不能转成需要的对象

<select id="???" resultMap="BaseResultMap">

综上得: 利用Mybatis-Plus的FastjsonTypeHandler可以更简便的达到目的。

经验分享 程序员 微信小程序 职场和发展