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

以上是自定义typehandler或者实体存成BLOB时用Byte[]。从数据库中取出来用String接收就可以了,以下是使用mybatis存入数据库

BLOB和CLOB都是大字段类型。java

BLOB是按二进制来存储的,而CLOB是能够直接存储文字的。sql

一般像图片、文件、音乐等信息就用BLOB字段来存储,先将文件转为二进制再存储进去。文章或者是较长的文字,就用CLOB存储.数据库

BLOB和CLOB在不一样的数据库中对应的类型也不同:
MySQL 中:clob对应text/longtext,blob对应blob
Oracle中:clob对应clob,blob对应blob

MyBatis提供了内建的对CLOB/BLOB类型列的映射处理支持。app

建表语句:测试

create table user_pics( id number primary key, name varchar2(50) , pic blob, bio clob ); 

照片(pic)能够是PNG,JPG或其余格式的。简介信息(bio)能够是学比较长的文字描述。默认状况下,MyBatis将CLOB类型的列映射到java.lang.String类型上、而把BLOB列映射到byte[]类型上。spa

public class UserPic{ private int id; private String name; private byte[] pic; private String bio; //setters & getters 
}

映射文件:code

<insert id="insertUserPic" parameterType="UserPic"> 
            <selectKey keyProperty="id" resultType="int" order="BEFORE"> select my_seq.nextval from dual </selectKey> insert into user_pics(id,name, pic,bio) values(#{id},#{name},#{pic},#{bio}) </insert> 

        <select id="getUserPicById" parameterType="int" resultType="UserPic"> select * from user_pics where id=#{id} </select>

映射接口:对象

public interface PicMapper { int insertUserPic(UserPic userPic); UserPic getUserPicById(int id); }

测试方法:blog

public void test_insertUserPic(){ String name = "tom"; String bio = "能够是很长的字符串"; byte[] pic = null; try { //读取用户头像图片
                File file = new File("src/com/briup/special/1.gif"); InputStream is = new FileInputStream(file); pic = new byte[is.available()]; is.read(pic); is.close(); } catch (Exception e){ e.printStackTrace(); } //准备好要插入到数据库中的数据并封装成对象
            UserPic userPic = new UserPic(name, pic , bio); SqlSession sqlSession = null; try{ sqlSession = MyBatisSqlSessionFactory.openSession(); SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class); mapper.insertUserPic(userPic); sqlSession.commit(); }catch (Exception e) { e.printStackTrace(); } } 

下面的getUserPic()方法将CLOB类型数据读取到String类型,BLOB类型数据读取成byte[]属性:接口

@Test public void test_getUserPicById(){ SqlSession sqlSession = null; try { sqlSession = MyBatisSqlSessionFactory.openSession(); SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class); UserPic userPic = mapper.getUserPicById(59); System.out.println(userPic.getId()); System.out.println(userPic.getName()); System.out.println(userPic.getBio()); System.out.println(userPic.getPic().length); } catch (Exception e) { e.printStackTrace(); } }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐