SpringBoot BaseTypeHandler将数据库中的类型转换成指定类型

将MySQL中的blob类型转换成Java中的String类型

//MappedJdbcTypes 指定数据库里的类型
@MappedJdbcTypes(JdbcType.BLOB)
//MappedTypes 指定要转换的类型
@MappedTypes(value = String.class)
public class BloBTypeHandler extends BaseTypeHandler<String> {

    private static final String DEFAULT_CHARSET = "UTF-8";


//一个setxxx方法,表示向PreparedStatement里面设置值。三个getxxx方法,一个是根据列名获取值,一个是根据列索引位置获取值,最后一个是存储过程
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setBlob(i, new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return blobToString(rs.getBlob(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return blobToString(rs.getBlob(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return blobToString(cs.getBlob(columnIndex));
    }


    private String blobToString(Blob blob) {
        String result = null;
        try {
            byte[] returnValue = null;
            if (null != blob) {
                returnValue = blob.getBytes(1, (int) blob.length());
            }
            if (null != returnValue) {
                result = new String(returnValue, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            throw new RuntimeException("Blob Encoding Error!");
        }
        return result;
    }
}

yml配置文件

mybatis:
  configuration:
    map-underscore-to-camel-case: true
   //指定BloBTypeHandler所在的包位置
  type-handlers-package: com.xxx.handler

mapper

    @Select("SELECT * FROM wx_public_user WHERE wxId=#{wxId} LIMIT #{page},#{pageNumber}")
    @Results(value = {@Result(property = "nickname", column = "nickname", javaType = String.class, jdbcType = JdbcType.BLOB)})
    List<WxMpUser> findWxID(String wxId, int page, int pageNumber);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr . zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值