BLOB和CLOB都是大字段类型。
BLOB是按二进制来存储的,而CLOB是可以直接存储文字的。
通常像图片、文件、音乐等信息就用BLOB字段来存储,先将文件转为二进制再存储进去。文章或者是较长的文字,就用CLOB存储.
BLOB和CLOB在不同的数据库中对应的类型也不一样:
MySQL 中:clob对应text/longtext,blob对应blob
Oracle中:clob对应clob,blob对应blob
MyBatis提供了内建的对CLOB/BLOB类型列的映射处理支持。
建表语句:
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[]类型上。
public class UserPic{
private int id;
private String name;
private byte[] pic;
private String bio;
//setters & getters
}
映射文件:
<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);
}
测试方法:
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();
}
}