mybatis 动态sql拼接

mybatis动态语句的元素及简单用法

if 作用:做条件判断 (但条件判断)

例:


<select id="selByName" resultType="com.ganin.entity.Account">
       select id,name,created,updated from account where 1=1
       <if test="name !=null and name !=''">
           and name like concat('%',#{name},'%')
       </if>
</select>

choose-when-otherwise 作用:条件选择(参考一下switch语句形式; 用来多条件分支判断)

例:

<select id="selByChoose" resultType="com.ganin.entity.Account">
        select id,name,created,updated,money from account where 1=1
        <choose>
            <when test="name !=null and name !=''">
                and name like concat('%',#{name},'%')
            </when>
            <when test="money !=null and money !=''">
                and money =#{money}
            </when>
            <otherwise>
                and isdeleted=1
            </otherwise>
        </choose>
    </select>

where、set 作用:辅助 (处理sql语句拼接问题)

where~if 例:

<select id="selByName" resultType="com.ganin.entity.Account">
    select id,name,created,updated from account
    <where>
    <if test="name !=null and name !=''">
        and name like concat('%',#{name},'%')
    </if>
    </where>
    </select>

set ~if 例:(在遇到逗号的时候,把对应的逗号去掉)

<update id="updateAccout" parameterType="com.ganin.entity.Account">
        update account
        <set>
            <if test="name !=null and name !=''">
               name=#{name},
            </if>
            <if test="money!=null and money!=''">
               money=#{money}
            </if>
        </set>
        where id=#{id}
    </update>

foreache 作用:循环 (作用时用来遍历集合,支持数组、List、Set接口集合)

<select id="selIn" resultType="com.ganin.entity.Account">
        select id,name,created,updated from account where name in
        <foreach collection="names" separator="," item="name" open="(" separator="," close=")">
        #{name}
       </foreach>
   </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值