IBATIS3的一些用法记录[整理]

动态sql语句

可以在xml配置文件中添加条件配置来动态拼接,调用sql语句,ibatis使用的ONGL表达式有四种元素 
if ,choose ,trim ,foreach

一、if

 <select id="user_list" parameterType="java.util.HashMap" resultType="test.date.user">
  select * from tb_common_keywords
  <where>
   <if test="id!=null"> 
     and id=#{id}
   </if>
   <if test="createTime!=null"> 
     and createtime=#{createTime}
   </if>
  </where>
  order by createtime desc
 </select>

 

二、choose,when,otherwise

<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”>
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <choose>
        <when test=”title != null”>
            AND title like #{title}
        </when>
        <when test=”author != null && author.name != null”>
            AND title like #{author.name}
        </when>
        <otherwise>
            AND featured = 1
        </otherwise>
    </choose>
</select>

 

三、trim,where,set

where标签可以动态加上where关键字:
<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”>
    SELECT * FROM BLOG
    <where>
        <if test=”state != null”>
            state = #{state}
        </if>
        <if test=”title != null”>
            AND title like #{title}
        </if>
        <if test=”author != null && author.name != null”>
            AND title like #{author.name}
        </if>
    </where>
</select>

这里也可以自定义trim元素来控制where等关键字,下面的trim配置等价于where标签

<trim prefix="WHERE" prefixOverrides="AND |OR ">
…
</trim>

这里trim标签文档上叙述的很模糊,大概意思是如果trim内的字符带有前缀“AND ”或者“OR ”那么去掉trim整段字符前面的where,否则添加where。

来看update语句中:

<update id="updateAuthorIfNecessary" parameterType="domain.blog.Author">
update Author
<set>
<if test="username != null">username=#{username},if>
<if test="password != null">password=#{password},if>
<if test="email != null">email=#{email},if>
<if test="bio != null">bio=#{bio}if>
</set>
where id=#{id}
</update>

set标签等价的trim标签配置为

<trim prefix="SET" suffixOverrides=",">
…
trim>
这里的trim标签原文叙述的很模糊,大概意思是trim中的字符带有后缀,的话那么就去掉trim整段字符前的set,否则添加set

foreach

<select id="selectPostIn" resultType="domain.blog.Post">
SELECT * FROM POST P WHERE ID in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>

item说明了集合内每一个元素的值,并在下面的sql中使用#{item} 来引用这个值 
index说明了集合内每一个元素的下标,并在下面的sql中使用#{index} 来引用这个值 
collection说明了集合元素的类型 
open是指转换后前面添加( 
separator表示每个集合元素之间以“,”分隔 
close在转换后最后添加)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值