Mybatis Blob和String互转,实现文件上传等。

这样的代码网上有很多,但是本人亲测有bug,

下面是我写的代码。望参考

 1 @MappedJdbcTypes(JdbcType.BLOB)
 2 public class BlobAndStringTypeHandler extends BaseTypeHandler<String> {
 3 
 4     private static final String DEFAULT_CHARSET = "UTF-8"; //感觉没屌用
 5 
 6     @Override
 7     public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
 8         ByteArrayInputStream bis = null;
 9         bis = new ByteArrayInputStream(parameter.getBytes());
10         ps.setBinaryStream(i, bis, parameter.getBytes().length); //网上都是直接paramter.length() 这样是不对的。 
11 
12     }
13 
14     @Override
15     public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
16         Blob blob = rs.getBlob(columnName);
17         byte[] returnValue = null;
18         String result = null;
19         if (null != blob) {
20             returnValue = blob.getBytes(1, (int) blob.length());
21         }
22         //将取出的流对象转为utf-8的字符串对象
23         if (null != returnValue) {
24             result = new String(returnValue);
25         }
26         return result;
27     }
28 
29     @Override
30     public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
31         Blob blob = rs.getBlob(columnIndex);
32         byte[] returnValue = null;
33         String result = null;
34         if (null != blob) {
35             returnValue = blob.getBytes(1, (int) blob.length());
36         }
37         //将取出的流对象转为utf-8的字符串对象
38         if (null != returnValue) {
39             result = new String(returnValue);
40         }
41         return result;
42     }
43 
44     @Override
45     public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
46         Blob blob = cs.getBlob(columnIndex);
47         byte[] returnValue = null;
48         String result = null;
49         if (null != blob) {
50             returnValue = blob.getBytes(1, (int) blob.length());
51         }
52         //将取出的流对象转为utf-8的字符串对象
53         if (null != returnValue) {
54             result = new String(returnValue);
55         }
56         return result;
57     }
58 }

下面简单介绍下 String.length()和String.getBytes().length()的区别:

String.length();字符串的长度,一个中文一个长度,就是一个字符

String.getBytes().length(): 字符串包含字节的长度,一个中文两个长度,就是两个字节

原文地址:https://www.cnblogs.com/haoerlv/p/9982244.html