场景
数据库中有一个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类型互相转换。