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"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM