jdk8+Mybatis3.5.0+Mysql读取LongBlob失败
问题:在mysql中存储base64,因为太长,基本就是几百K,所以用longBlob
描述:在mysql中,LongBlob、blob算是二进制流文件了,所以用普通的数据格式是不行的,这里用TypeHandler解决,有其他觉得方案欢迎在下方留言
解决:
Handler代码
import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.sql.*; public class MyBlobTypeHandler extends BaseTypeHandler<String> { // 指定字符集 private static final String DEFAULT_CHARSET = "utf-8"; @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { ByteArrayInputStream bis; try { // 把String转化成byte流 bis = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Blob Encoding Error!"); } ps.setBinaryStream(i, bis, parameter.length()); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { return getResult(rs.getBlob(columnName)); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return getResult(cs.getBlob(columnIndex)); } @Override public String getNullableResult(ResultSet rs, int columnName) throws SQLException { return getResult(rs.getBlob(columnName)); } private String getResult(Blob blob) throws SQLException { byte[] returnValue = null; if (null != blob) { returnValue = blob.getBytes(1, (int) blob.length()); } try { // 把byte转化成string if (null != returnValue) { return new String(returnValue, DEFAULT_CHARSET); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("Blob Encoding Error!"); } return null; } }
mybatis XML代码
<result property="signature" column="signature" typeHandler="com.kenary.config.MyBlobTypeHandler"/>
我不作恶
但有权拒绝为善
我不赞同
但是我捍卫你不为善的权力