Mybatis之blob与String转换

场景

数据库中有一个blob字段,在java中用String接收。使用如下方式读取:

<select id="find" resultType="com.example.bean.User">
  select id, name, experience, createTime
  from user
</select>

如果这里的experience字段为blob类型,那么取出来的数据就会乱码。

解决方法是自定义一个TypeHandler,通过继承BaseTypeHandler类实现。如下。

BlobToStringTypeHandler

先看xml应用:

<resultMap id="UserResultMap" type="com.example.bean.User">
  <id property="id" column="id"></id>
  <result property="name" column="name"></result>
  <result property="experience" column="experience" typeHandler="com.example.handler.BlobToStringTypeHandler"></result>
  <result property="createTime" column="createTime"></result>
</resultMap>

<select id="find" resultMap="UserResultMap">
  select id, name, experience, createTime
  from user
</select>

再看BlobToStringTypeHandler代码:

package com.example.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;

public class BlobToStringTypeHandler extends BaseTypeHandler<String> {
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, parameter);
  }

  @Override
  public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    Blob blob = rs.getBlob(columnName);
    return new String(blob.getBytes(1, (int)blob.length()));
  }

  @Override
  public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    Blob blob = rs.getBlob(columnIndex);
    return new String(blob.getBytes(1, (int)blob.length()));
  }

  @Override
  public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    Blob blob = cs.getBlob(columnIndex);
    return new String(blob.getBytes(1, (int)blob.length()));
  }
}

以上,通过继承BaseTypeHandler并实现其方法,将sql的blob类型字段与java的String类型互相转换。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值