mybatis 處理CLOB/BLOB類型數據

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(); } }
相關文章
相關標籤/搜索