zoukankan      html  css  js  c++  java
  • 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"/>

    我不作恶

    但有权拒绝为善

    我不赞同

    但是我捍卫你不为善的权力

  • 相关阅读:
    20165339 预备作业3 Linux安装及学习
    20165339 学习基础和c语言基础调查
    20165339 我期望的师生关系
    2018-2019-1 20165332 《信息安全系统设计基础》第3周学习总结
    2018-2019-1 20165332 《信息安全系统设计基础》第2周学习总结
    2018-2019-1 20165332 《信息安全系统设计基础》第1周学习总结
    20165332 2017-2018-2《Java程序设计》课程总结
    20165332实验五 网络编程与安全
    20165332实验四 Android开发基础
    20165332第十周课下作业
  • 原文地址:https://www.cnblogs.com/HackerBlog/p/10697062.html
Copyright © 2011-2022 走看看