Mybatis解决数据库Blob类型存储与读取问题

目录

    • 1.Blob介绍
    • 2.自定义Blob类型处理器
    • 3.编写查询语句

1.Blob介绍

首先,先简单介绍下数据库Blob字段,Blob(Binary Large Object)是指二进制大对象字段,顺带介绍下Clob类型,Clob(Character Large Object)是指大字符对象。其中Blob是为存储大的二进制数据而设计的,而Clob是为存储大的文本数据而设计的。JDBC的PreparedStatement和ResultSet都提供了相应的方法来支持Blob和Clob操作,Mybatis各版本也支持对Blob或者Clob的存储以及读取操作,本文详细介绍Mybatis中Blob字段的操作。

2.自定义Blob类型处理器

MyBatis框架提供了一个BaseTypeHandler类,该类用于用户自定义一些字段类型,我们可以用这个类来操作Blob类型数据。该类有两个重要方法,setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)getNullableResult(ResultSet rs, String columnName) 。前者提供开发者处理insert、update、delete语句结构的数据,ps参数为JDBC的预编译对象,i参数为SQL参数的占位符,parameter参数为当前Blob的长字符串,jdbcType为数据库字段类型。后者为查询语句返回数据的处理,rs参数为返回的数据集,columnName为字段名字。下面详细显示自定义Blob处理类代码。

public class BlobTypeHandler extends BaseTypeHandler<String> {
    public void setNonNullParameter(PreparedStatement ps, int i,  
            String parameter, JdbcType jdbcType) throws SQLException {  
        //声明一个输入流对象
        ByteArrayInputStream bis;  
        try {  
            //把字符串转为字节流
            bis = new ByteArrayInputStream(parameter.getBytes('utf-8'));  
        } 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 {  
        Blob blob = (Blob) rs.getBlob(columnName);  
        byte[] returnValue = null;  
        if (null != blob) {  
            returnValue = blob.getBytes(1, (int) blob.length());  
        }  
        try {  
            //将取出的流对象转为utf-8的字符串对象
            return new String(returnValue, 'utf-8');  
        } catch (UnsupportedEncodingException e) {  
            throw new RuntimeException("Blob Encoding Error!");  
        }  
    }  
    }

3.编写查询语句

在MyBatis的配置文件中写一条查询语句,查询大字段数据,我这里讲content字段作为演示的Blob类型。

<select id="queryByList" parameterType="Map" resultMap="queryBaseResultMap">
    select  id ,title,type,content,author from my_blob 
    where 1 = 1 order by ${orderByClause}
 select>
 <resultMap id="queryBaseResultMap" type="com.lst.model.MyBlob" >
    <id column="Id" property="id" jdbcType="INTEGER" />
    <result column="type" property="type" jdbcType="INTEGER" />
    <result column="Title" property="title" jdbcType="VARCHAR" />
    <result column="Author" property="author" jdbcType="VARCHAR" />
    <result column="Content" property="content" typeHandler="com.lst.utils.BlobTypeHandler"/> 
resultMap>

ok,本文就讲到这么多,大字段在目前的系统开发中应用很广泛,如图片上传、短视频处理、以及当下的自媒体的图文并茂的内容呈现等等。

你可能感兴趣的:(MyBatis,Blob,Java,JDBC,Java技术)