场景

表结构中有一个大字段BLOB用于存放富文本,写入和读取都希望是String类型

代码

增加typeHandler类型处理类

package com.example.util;

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()));
  }
}

mapper.xml的resultMap中大字段配置对应的typeHandler

<result column="content" property="content" typeHandler="com.example.util.BlobToStringTypeHandler" />