詳解Ibatis寫CLOB數(shù)據(jù)
Ibatis是一個高效,方便,易于學(xué)習(xí)的數(shù)據(jù)訪問組件,在性能上比hibernate高,學(xué)習(xí)難度也比hibernate和jdo要低,而且它比直接使用jdbc方便和易于維護(hù)。所以Ibatis深入大家的喜愛,一些對性能有更高的要求的系統(tǒng)(如保險,金融行業(yè)系統(tǒng)),或改造遺留系統(tǒng)時,Ibatis是數(shù)據(jù)訪問組件的首選。
在使用Oracle數(shù)據(jù)庫時,讀取CLOB和BLOB等大類型的數(shù)據(jù)一直是個比較犯難的事,一般都是通過JDBC代碼來實現(xiàn)對CLOB和BLOB數(shù)據(jù)的讀寫,效果和性能都是最好的,但是代碼也相當(dāng)復(fù)雜,且代碼難以重用。
公司的項目正好有這方面的需要,要求我給予解決。在網(wǎng)上找了一些方法,好多不能滿足需求,而且都是轉(zhuǎn)載,于是看了下ibatis包,發(fā)現(xiàn)ibatis里面已經(jīng)封裝了類,只要直接使用即可。
有兩種方式實現(xiàn):
1.通過配置ParameterMap和ResultMap來實現(xiàn)對LOB類型的讀寫
1.1 java代碼
假設(shè)java類中有個字符串屬性
- private String detail; // 詳細(xì)描述
1.2 sqlmap配置
- <parameterMap class="Description" id="DescriptionParam">
- <parameter property="detail" javaType="java.lang.String" jdbcType="NCLOB" typeHandler="com.ibatis.sqlmap.engine.type.ClobTypeHandlerCallback"/>
- <parameter property="id" javaType="java.lang.Long"/>
- < span>parameterMap>
注意:因為使用了ParameterMap作為輸入?yún)?shù),在插入語句中用?號來代替屬性值(如:#detail#)
新增數(shù)據(jù)時配置
- <insert id="addDescription" parameterClass="Description" >
- insert into description
- (id,
- detail)
- values(#?#,#?#)
- ]]>
- <selectKey resultClass="java.lang.Long" keyProperty="id" type="pre">
- select SEQ_description_ID.NEXTVAL from DUAL
- < span>selectKey>
- < span>insert>
更新數(shù)據(jù)時配置
- <update id="updateDescription" parameterClass="Description" >
- update description set tab_detail = #?# where id=#?#
- < span>update>
2. 通過parameterClass傳入?yún)?shù)(推薦)
2.1 java代碼
假設(shè)java類中有個字符串屬性
- private String detail; // 詳細(xì)描述
2.2 sqlmap配置
新增數(shù)據(jù)時配置
- <insert id="addDescription" parameterClass="Description" >
- insert into description (id, detail)
- values (#id#, #tabDetail,handler=com.ibatis.sqlmap.engine.type.ClobTypeHandlerCallback#)
- ]]>
- <selectKey resultClass="java.lang.Long" keyProperty="id" type="pre">
- select SEQ_description_ID.NEXTVAL from DUAL
- < span>selectKey>
- < span>insert>
更新數(shù)據(jù)時配置
- <update id="updateDescription" parameterClass="Description" >
- update description
- <dynamic prepend="set" >
- <isNotNull prepend="," property="detail" >
- tab_detail = #detail,handler=com.ibatis.sqlmap.engine.type.ClobTypeHandlerCallback#
- < span>isNotNull>
- < span>dynamic>
- where id=#id#
- < span>update>
ibatis還存在很多的typeHandler,大家自己可以看看
【編輯推薦】