政府門戶網(wǎng)站建設(shè)工作總結(jié)杭州seo博客有哪些
Mybatis 處理 CLOB/BLOB 類型數(shù)據(jù)
BLOB 和 CLOB 都是大型字段類型。
BLOB通過二進(jìn)制存儲(chǔ),而CLOB可以直接存儲(chǔ)文本。
通常,圖片、文件、音樂等信息存儲(chǔ)在 BLOB 字段中。首先,文件是轉(zhuǎn)換為二進(jìn)制,然后存儲(chǔ)在。文章或較長(zhǎng)的文本存儲(chǔ)在 CLOB 中。
不同數(shù)據(jù)庫中相應(yīng)的 BLOB 和 CLOB 類型也不同:
在MySQL中,clob對(duì)應(yīng)于text/longtext,blob對(duì)應(yīng)于blob。
在Oracle中:clob 對(duì)應(yīng)于 clob,blob 對(duì)應(yīng)于 blob。
MyBatis 為 CLOB/BLOB 類型的列提供了內(nèi)置的映射支持。
1、創(chuàng)建表語句:
create table user_pics(id number primary key,name varchar2(50) ,pic blob,bio clob
);
2、圖片(PICS)可以是PNG,JPG或其他格式。簡(jiǎn)要信息(bio)可以是很長(zhǎng)的文本描述。默認(rèn)情況下,MyBatis 將 CLOB 列映射到 java.lang.String 類型,將 BLOB 列映射到 byte [] 類型。
public class UserPic{private int id;private String name;private byte[] pic;private String bio;//setters & getters
}
3、Map 文件:
<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>
4、Mapping 接口:
public interface PicMapper {int insertUserPic(UserPic userPic);UserPic getUserPicById(int id);
}
5、測(cè)試方法:
@Test
public void test_insertUserPic(){String name = "tom";String bio = "Can be a very long string";byte[] pic = null;try {//Read user pictureFile 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 objectUserPic 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();}
}
6、以下 getUserPic() 方法將 CLOB 類型數(shù)據(jù)讀取為字符串類型,將 BLOB 類型數(shù)據(jù)讀取為字節(jié) []屬性:
@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();}
}