您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页Mybatis之blob与String转换

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类型互相转换。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务