詳解Ibatis寫CLOB數據
Ibatis是一個高效,方便,易于學習的數據訪問組件,在性能上比hibernate高,學習難度也比hibernate和jdo要低,而且它比直接使用jdbc方便和易于維護。所以Ibatis深入大家的喜愛,一些對性能有更高的要求的系統(如保險,金融行業系統),或改造遺留系統時,Ibatis是數據訪問組件的首選。
在使用Oracle數據庫時,讀取CLOB和BLOB等大類型的數據一直是個比較犯難的事,一般都是通過JDBC代碼來實現對CLOB和BLOB數據的讀寫,效果和性能都是最好的,但是代碼也相當復雜,且代碼難以重用。
公司的項目正好有這方面的需要,要求我給予解決。在網上找了一些方法,好多不能滿足需求,而且都是轉載,于是看了下ibatis包,發現ibatis里面已經封裝了類,只要直接使用即可。
有兩種方式實現:
1.通過配置ParameterMap和ResultMap來實現對LOB類型的讀寫
1.1 java代碼
假設java類中有個字符串屬性
- private String detail; // 詳細描述
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作為輸入參數,在插入語句中用?號來代替屬性值(如:#detail#)
新增數據時配置
- <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>
更新數據時配置
- <update id="updateDescription" parameterClass="Description" >
- update description set tab_detail = #?# where id=#?#
- < span>update>
2. 通過parameterClass傳入參數(推薦)
2.1 java代碼
假設java類中有個字符串屬性
- private String detail; // 詳細描述
2.2 sqlmap配置
新增數據時配置
- <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>
更新數據時配置
- <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,大家自己可以看看
【編輯推薦】