mybatis blob与clob处理

本文详细介绍了如何在MyBatis框架中处理常见的SQL场景,包括利用insert语句返回Oracle序列主键、条件查询时入参不固定的动态SQL配置、以及如何处理CLOB和BLOB类型数据。同时,展示了如何通过动态SQL实现灵活的查询和更新操作,以及如何在SQL中使用foreach循环高效地构建复杂条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


有幸在项目中用到了这个框架的大部分高级特性,比如一二级缓存,动态sql等等。真正的让我爱上了这个框架,本篇说一说一些典型的sql场景,看看这个框架是怎么来处理的。
insert语句返回oracle序列主键:
最普通的,我的表主键是序列来生成(由于是oracle),所以我需要插入时候生成序列主键并且返回,以下为配置:
1<insert id="save"parameterType="cn.com.blossomframework.services.core.domain.Navigation">
2  <selectKey resultType="int"keyProperty="id"order="BEFORE">
3    select s_navigation.nextval as id from dual
4  </selectKey>
5  insert into navigation (
6  id,name,type,order,isshow,cid,portletid,uuid)
7  values (
8  #{id},#{name},#{type},#{order},#{isshow},#{cid},#{portletid},#{uuid})
9</insert>


selectKey中order属性的值是不同的,BEFORE先选择主键,设置keyProperty的值然后执行插入语句。 AFTER是先执行插入语句,然后执行selectKey。

条件查询时候的入参不固定 :
01<select id="findAll"resultMap="navigations">
02    select * from navigation
03    <where>
04        <iftest="portetid != null">
05        login_name=#{portletid}
06        </if>
07        <iftest="uuid != null">
08        and name=#{uuid}
09        </if>
10    </where>
11</select>

如果有uuid和portletid这任意其中之一的入参,则执行条件查询,否则为普通查询 

1<update id="update"parameterType="int">
2   update navigation
3   <set>
4        <iftest="name != null">name=#{name},</if>
5        <iftest="isshow != null">isshow=#{isshow},</if>
6        <iftest="cid != null">cid=#{cid}</if>
7   </set>
8   where id=#{id}
9</update>

 update方法的不固定入参

 处理clob,blob类型,第一篇博客blablabla写了一堆代码,在这里简单配置一个typehandler就搞定
1<update id="update"parameterType="cn.com.blossomframework.services.core.domain.WebContent">
2   update webcontent
3   set title=#{title},content=#{content,typeHandler=org.apache.ibatis.type.ClobTypeHandler}
4   where id=#{id}
5</update>

blob的类型处理器为 B lobTypeHandler(低版本的使用的是spring orm包的typehandler,只支持mybatis2.0版本,现在MyBatis已经3.2了,Spring太不给面子了,和hibernate是好基友,spring已经支持hibernate4了)

select * from 表名 where 列 in (1,2,3)
1<select id="findAns"resultMap="announcements">
2  select *
3  from navigation
4  where idref in
5  <foreach item="cid"index="index"collection="array"
6      open="("separator=","close=")">
7        #{cid}
8  </foreach>
9</select>
入参为cid,index为循环的index,collection定义入参类型,array代表数组,也可以为list,显而易见open,separator和close是帮你拼接sql的,碉堡了有木有!

还有更多的动态sql高级应用和关联查询,具体参看git上的官方文档! http://mybatis.github.io/mybatis-3/zh/configuration.html#settings




使用Mybatis时,关于字段为Blob时,首先你的pojo/domian/to,就是与数据库对应的对象Class中
属性肯定是byte[],若是Clob,那就为char[],这个不用解释。

问题:插入数据没有问题,但是查询就傻了,得到的总是为Null.
解决:返回类型建立一个resultMap
<result column="HTML_CODE" property="htmlCode" jdbcType="BLOB"  typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>

如上所示,问题解决。(当然Clob也是一样,改一下反序列化的类,typeHandler就行)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值