MyBatis中mapper的if,where,set等标签的用法

if---- 基本都是用来判断值是否为空

<if test="userCustom != null">
        <if test="userCustom.username != null and userCustom.username != ''"><!-- 注意and不能大写 -->
            and username = #{userCustom.username}
        </if>
        <if test="userCustom.sex != null and userCustom.sex != ''">
            and sex = #{userCustom.sex}
        </if>
    </if> 

where ---- 用来去掉多条件查询时,开头多余的and

 select * from user
    <where>
    <!-- 引用Sql片段 -->
    <include refid="query_user_where"></include>
    <!-- 在这里还要引用其它的sql片段 -->
    <!-- 
    where 可以自动去掉条件中的第一个and
    -->
    <!--    <if test="sex != null and sex != ''">
            and sex = #{sex}
        </if>
        <if test="id != null">
            and id = #{id}
        </if> -->

    </where>
</select>

set ----set标记是mybatis提供的一个智能标记,我一般将其用在修改的sql中,例如以下情况:

 update user 

    <set>

      <if test="name != null and name.length()>0">name = #{name},</if>

      <if test="gender != null and gender.length()>0">gender = #{gender},</if>

    </set>

    where id = #{id}

  </update>

在上述的代码片段当中,假如说现在三个字段都有值得话,那么上面打印的SQL语句如下:

update user set name=‘xxx’ , gender=‘xx’ where id=‘x’

在上面标红的地方是没有逗号的,也就是说set标记已经自动帮助我们把最后一个逗号给去掉了

foreach ---- 用来遍历数组或者集合

     <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or" >
    每次遍历需要拼接的串
                id= #{user_id}
        </foreach>
 </if>

需求:SELECT * FROM USER WHERE id=1 OR id=10 OR id=16
或者:SELECT * FROM USER WHERE id IN(1,10,16)

其中,collection:指定输入对象中集合属性,item: 每个遍历生成对象,open:开始遍历时拼接串,close: 结束遍历是拼接的串,separator: 遍历的两个对象中需要拼接的串
 

<if test="ids != null">     
    <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">
                id= #{user_id}
    </foreach>
</if>

choose
有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

例如下面例子,同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。
 

<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
            </when >  
            <when test="sex != null and sex != '' ">  
                AND u.sex = #{sex, jdbcType=INTEGER}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday, jdbcType=DATE}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>  

猜你喜欢

转载自blog.csdn.net/weixin_42354735/article/details/86668225