BLOB和CLOB都是大字段类型。
BLOB是按二进制来存储的,而CLOB是可以直接存储文字的。
通常像图片、文件、音乐等信息就用BLOB字段来存储,先将文件转为二进制再存储进去。文章或者是较长的文字,就用CLOB存储.
BLOB和CLOB在不同的数据库中对应的类型也不一样:
MySQL 中:clob对应text/longtext,blob对应blob
Oracle中:clob对应clob,blob对应blob
MyBatis提供了内建的对CLOB/BLOB类型列的映射处理支持。
建表语句:
create tableuser_pics(
idnumber primary key,
namevarchar2(50) ,
pic blob,
bio clob
);
照片(pic)可以是PNG,JPG或其他格式的。简介信息(bio)可以是学比较长的文字描述。默认情况下,MyBatis将CLOB类型的列映射到java.lang.String类型上、而把BLOB列映射到byte[]类型上。
public classUserPic{private intid;privateString name;private byte[] pic;privateString bio;//setters & getters
}
映射文件:
select my_seq.nextval from dualinsert into user_pics(id,name, pic,bio)
values(#{id},#{name},#{pic},#{bio})
select * from user_pics where id=#{id}
映射接口:
public interfacePicMapper {intinsertUserPic(UserPic userPic);
UserPic getUserPicById(intid);
}
测试方法:
public voidtest_insertUserPic(){
String name= "tom";
String bio= "可以是很长的字符串";byte[] pic = null;try{//读取用户头像图片
File file = new File("src/com/briup/special/1.gif");
InputStream is= newFileInputStream(file);
pic= new byte[is.available()];
is.read(pic);
is.close();
}catch(Exception e){
e.printStackTrace();
}//准备好要插入到数据库中的数据并封装成对象
UserPic userPic = newUserPic(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[]属性:
@Testpublic voidtest_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();
}
}