今天遇到这个问题也是很奇葩,一开始在转换类里面疯狂打断点,打印出来的也是乱码。还有就是我只挑了两三条数据搁那边测,导致一开始找的问题的方向就有点偏。
直接上解决办法!
public class MyBlobTypeHandler extends BaseTypeHandler<String> {
private static Logger logger = LoggerFactory.getLogger(MyBlobTypeHandler.class);
//###指定字符集
private static final String UTF8_charset = "UTF-8";
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
byte[] bytes = new byte[1024];
try {
// 把String转化成byte流
bytes = s.getBytes(UTF8_charset);
} catch (UnsupportedEncodingException e) {
logger.error("String 转 blob 失败...msg: {}", e.getMessage());
throw new RuntimeException("Blob Encoding Error!");
}
preparedStatement.setBytes(i, bytes);
}
@Override
public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
if(resultSet.getBytes(s) == null){
return null;
}
byte[] returnValue = resultSet.getBytes(s);
try {
// 把byte转化成string
return new String(returnValue, UTF8_charset);
} catch (UnsupportedEncodingException e) {
logger.error("blob 转 String 失败...msg: {}", e.getMessage());
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
if(resultSet.getBytes(i) == null) {
return null;
}
byte[] returnValue = resultSet.getBytes(i);
try {
return new String(returnValue, UTF8_charset);
} catch (UnsupportedEncodingException e) {
logger.error("blob 转 String 失败...msg: {}", e.getMessage());
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return null;
}
}
请看好这段代码:
// 错误的是
byte[] bytes = null;
// 修改为
byte[] bytes = new byte[1024];
没错,基本的数据长度小了!我当时也是没注意发现到有的存储大小只是byte而有的已经是kb了。修改了一下,就好了.....