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
);
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);
}
@Test
public void test_insertUserPic(){
String name = "tom";
String bio = "Can be a very long string";
byte[] pic = null;
try {
//Read user picture
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();
}
//Prepare the data to be inserted into the database and encapsulate it as an object
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();
}
}
@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();
}
}