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(); } }