将MySQL中的blob类型转换成Java中的String类型
//MappedJdbcTypes 指定数据库里的类型
@MappedJdbcTypes(JdbcType.BLOB)
//MappedTypes 指定要转换的类型
@MappedTypes(value = String.class)
public class BloBTypeHandler extends BaseTypeHandler<String> {
private static final String DEFAULT_CHARSET = "UTF-8";
//一个setxxx方法,表示向PreparedStatement里面设置值。三个getxxx方法,一个是根据列名获取值,一个是根据列索引位置获取值,最后一个是存储过程
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
try {
ps.setBlob(i, new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET)));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return blobToString(rs.getBlob(columnName));
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return blobToString(rs.getBlob(columnIndex));
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return blobToString(cs.getBlob(columnIndex));
}
private String blobToString(Blob blob) {
String result = null;
try {
byte[] returnValue = null;
if (null != blob) {
returnValue = blob.getBytes(1, (int) blob.length());
}
if (null != returnValue) {
result = new String(returnValue, DEFAULT_CHARSET);
}
} catch (Exception e) {
throw new RuntimeException("Blob Encoding Error!");
}
return result;
}
}
yml配置文件
mybatis:
configuration:
map-underscore-to-camel-case: true
//指定BloBTypeHandler所在的包位置
type-handlers-package: com.xxx.handler
mapper
@Select("SELECT * FROM wx_public_user WHERE wxId=#{wxId} LIMIT #{page},#{pageNumber}")
@Results(value = {@Result(property = "nickname", column = "nickname", javaType = String.class, jdbcType = JdbcType.BLOB)})
List<WxMpUser> findWxID(String wxId, int page, int pageNumber);