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

    我不作恶

    但有权拒绝为善

    我不赞同

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

  • 相关阅读:
    第一讲 jQuery入门
    Log4j日志记录
    第四讲 Hibernate 缓存管理
    第一讲 Hibernate 简介
    第三讲 Spring 持久层封装、事务控制
    对 PInvoke 函数的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标
    善用 C# 3.0 Extensions 方法
    .net 下如何将文档文件(Word, Pdf等) 中的文本提取出来(转)
    vs2010常用快捷键 (转)
    Silverlight 视频学习札记(一)
  • 原文地址:https://www.cnblogs.com/HackerBlog/p/10697062.html
Copyright © 2011-2022 走看看