首页 > 数据库 >Mybatis动态SQL映射

Mybatis动态SQL映射

时间:2023-03-30 15:03:10浏览次数:43  
标签:userName trim userCode 映射 SQL Mybatis WHERE id 结构


Mybatis动态SQL映射

  • 动态SQL映射
  • 1.if 结构 test里面的 and 或 or 必须小写
  • 2.trim-if 多条件结构
  • 3.where-if 多条件结构
  • 4.choose-when-otherwise 多选一结构
  • 5.foreach 循环结构 代替 WHERE id IN (?,?...)
  • 6. set-if 或 trim-if 修 改数据结构

动态SQL映射

1.if 结构 test里面的 and 或 or 必须小写

<!-- test里面放判断条件 -->
<if test="id != null and id != -1">
    WHERE id=#{id}
</if>

2.trim-if 多条件结构

<!-- prefix:条件前缀    prefixOverrides:前缀覆盖AND|OR -->
<trim prefix="WHERE" prefixOverrides="AND|OR">
    <if test="id != null">
        AND id=#{id}
    </if>
    <if test="name != null">
        AND userName like CONCAT('%',#{name},'%')
    </if>
</trim>

3.where-if 多条件结构

<where>
    <if test="id != null">
        AND id=#{id}
    </if>
    <if test="name != null">
        AND userName like CONCAT('%',#{name},'%')
    </if>
</where>

4.choose-when-otherwise 多选一结构

<choose>
    <when test="id!=null">
        WHERE id=#{id}
    </when>
    <when test="name!=null">
        WHERE userName like CONCAT('%',#{name},'%')
    </when>
    <otherwise>
        <!-- 上面条件都不满足时执行 -->
    </otherwise>
</choose>

5.foreach 循环结构 代替 WHERE id IN (?,?..)

WHERE id IN
<!-- collection:集合名称 item:每一个元素 open:sql开始部位 separator:中间分隔符 close:sql结束部位 -->
<foreach collection="ids" item="id" open="(" separator=","
    close=")">
    #{id}
</foreach>

6. set-if 或 trim-if 修 改数据结构

<update id="setUser">
    UPDATE smbms_user
    <set>
        <if test="userCode != null and userCode != ''">userCode = #{userCode} , </if>
        <if test="userName != null">userName = #{userName}, </if>
    </set>
    WHERE id = #{id}
    <!-- 或 -->
    <!-- prefix:前缀  suffixOverrides:修改的后缀覆盖  suffix:后缀 -->
    <trim prefix="SET" suffixOverrides="," suffix="WHERE id = #{id}">
        <if test="userCode != null">userCode = #{userCode} , </if>
        <if test="userName != null">userName = #{userName}, </if>
    </trim>
</update>


标签:userName,trim,userCode,映射,SQL,Mybatis,WHERE,id,结构
From: https://blog.51cto.com/loveddz/6159587

相关文章