1. 程式人生 > >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型別互相轉換。