解决办法:
对于注解形式的sql:
@Select("select * from sys_user where id = #{id}")
@Results({@Result(column = "info", property = "info", typeHandler = CustomizeBlobToStringHandler.class)})
User selectCustomAnnotation(@Param("id") Long id);
对于xml形式的sql
<resultMap id="BaseResultMap" type="com.samubo.plus.quickstart.pojo.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="age" property="age"/>
<result column="info" property="info" javaType="java.sql.Blob" typeHandler="com.samubo.plus.quickstart.handler.CustomizeBlobToStringHandler"/>
</resultMap>
<select id="selectCustomXml" resultType="com.samubo.plus.quickstart.pojo.User" >
select * from sys_user where id = #{id}
</select>
@Data
@TableName(value = "sys_user", autoResultMap=true)
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(typeHandler = CustomizeBlobToStringHandler.class, jdbcType = JdbcType.BLOB)
private String info;
CustomizeBlobToStringHandler:
public class CustomizeBlobToStringHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
throws SQLException {
byte[] bytes = parameter.getBytes(StandardCharsets.UTF_8);
ps.setBlob(i, new ByteArrayInputStream(bytes), bytes.length);
}
@Override
public String getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
return getConvertResult(resultSet.getBlob(columnName));
}
@Override
public String getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
return getConvertResult(resultSet.getBlob(columnIndex));
}
@Override
public String getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
return getConvertResult(callableStatement.getBlob(columnIndex));
}
private String getConvertResult(Blob blob) throws SQLException {
if (blob == null) {
return null;
}
return new String(blob.getBytes(1, (int) blob.length()), StandardCharsets.UTF_8);
}
}