天天看点

MyBatis动态sql语句使用

一、MyBatis动态语句分为4种元素:

元素 作用 描述
if 条件判断 单条件判断
choose(when、otherwise) 条件选择,相当Java when 多条件分支判断
where、set 辅助 处理sql语句拼接问题
foreache 循环 循环

二、Mybatis动态sql语句使用方式、例子

1、if元素,如下

<select id="selByName" resultType="yuan.yuanmybatis.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>
           

2.choose

<select id="selByChoose" resultType="yuan.yuanmybatis.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 name =#{money}
            </when>
            <otherwise>
                and isdeleted=1
            </otherwise>
        </choose>
    </select>
           

3、where元素,细心的读者会发现1、2点会有一个1=1,如果没有1=1,那么会变成如下错误语句:

select id,name,created,updated,money from account where and name like concat('%',#{name},'%') 
           

这个时候我们可以用where元素处理sql:

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

where元素在里面的条件成立的时候,才会加入where这个sql关键字。

4、trim元素可以帮助我们去掉一下and、or等,prefix代表语句前缀, prefixOverrides代表要去掉的字符串

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

5、set元素,它可以在遇到逗号的时候,把对应的逗号去掉

<update id="updateAccout" parameterType="yuan.yuanmybatis.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>
           

6、foreach元素,它时一个循环语句,作用时用来遍历集合,支持数组、List、Set接口集合

<select id="selIn" resultType="yuan.yuanmybatis.entity.Account">
        select id,name,created,updated from account where name in
        <foreach collection="nameList" index="index" item="name" open="(" separator="," close=")">
        #{name}
       </foreach>
   </select>
           

继续阅读