前言:

mybatis设用场景比较多,可以代替java代码,但还是不建议写过多的逻辑。最近想写一个关于常用函数使用,针对以前没用过的,可能还有很多没写到,可以提上来

一、if else使用

<if test="params.awardId != null and params.awardId != '' ">
        <choose>
            <when test="params.awardId == 4">
                        and award_id in(4,16)
            </when>
             <when test="params.awardId == 7">
                        and award_id in(7,12)
             </when>
             <otherwise>
                        and award_id = #{params.awardId}
             </otherwise>
         </choose>
</if>

二、foreach批量插入

<!--批量插入用户-->
<insert id="insertBusinessUserList" parameterType="java.util.List">
    insert into `business_user` (`id` , `user_type` , `user_login` )
    values
    <foreach collection="list" index="index" item="item" separator=",">
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <choose>
                <when test="item.id != null and item.id !=''">
                    #{item.id,jdbcType=CHAR},
                </when>
                <otherwise>
                    '',
                </otherwise>
            </choose>
            <choose>
                <when test="item.userType != null and item.userType !=''">
                    #{item.userType,jdbcType=VARCHAR},
                </when>
                <otherwise>
                    '',
                </otherwise>
            </choose>
        </trim>
    </foreach>
</insert>

三、String字符串类型的数组foreach循环使用

<if test="advertChannelUser != null and advertChannelUser != '-1'">
   and advert_channel_user in
  <foreach item="status" collection="advertChannelUser.split(',')" open="(" separator="," close=")">
    #{status}
  </foreach>
</if>

四、String集合类型foreach循环使用

参数:List list

 ai.uid0 in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
  #{item}
</foreach>

五、List数组foreach循环使用

<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
     #{item}
</foreach>