Mybatis Blob和String互轉,實現文件上傳等。

這樣的代碼網上有不少,可是本人親測有bug,app

下面是我寫的代碼。望參考ide

 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()的區別:spa

String.length();字符串的長度,一箇中文一個長度,就是一個字符code

String.getBytes().length(): 字符串包含字節的長度,一箇中文兩個長度,就是兩個字節對象

相關文章
相關標籤/搜索