MyBatis动态SQL

发布于:2025-07-19 ⋅ 阅读:(14) ⋅ 点赞:(0)

1. 动态SQL

2. set/where+if

        SET代码演示

<update id="updateUser" parameterType="com.zb.entity.User">
        UPDATE USER
         <set>
             <if test="loginPwd!=null and loginPwd!=''">
                 login_pwd =#{loginPwd},
             </if>
             <if test="roleId!=null">
                 role_id = #{roleId}
             </if>
         </set>
         WHERE id = #{id}
    </update>

根据传入方法传入的参数进行判断,然后拼接sql语句,同时myBatis会整合语句并修正语句中的小错误,如逗号等,比如在role_id = #{roleId}后加上逗号,拼接出来的sql语句会自动将逗号删除

        WHERE代码演示

        通用where语句

<sql id="where_sql">
        <where>
            <if test="uid!=null">
                a.`uid`=#{uid}
            </if>
            <if test="type!=null and type!=''">
                AND a.type=#{type}
            </if>
            <if test="procc!=null">
                AND procc=#{procc}
            </if>
        </where>
    </sql>

        使用include+refid来放入不同的sql语句得到拼接的效果

<select id="page" resultMap="baseResultMap" parameterType="com.zb.vo.PageParam">
        SELECT a.*, u.`user_name` FROM alarm a LEFT JOIN USER u ON a.`uid` = u.`id`
        <include refid="where_sql"/>
        LIMIT #{start} , #{size}
    </select>
<select id="count" parameterType="com.zb.vo.PageParam" resultType="int">
        SELECT count(*) FROM alarm a LEFT JOIN USER u ON a.`uid` = u.`id`
        <include refid="where_sql"/>
    </select>

3. trim

核心属性

  • prefix:在整个内容前添加的字符串(如 WHERESET)。
  • suffix:在整个内容后添加的字符串(如 ORDER BY id)。
  • prefixOverrides:移除内容开头的匹配字符串(如多余的 ANDOR)。
  • suffixOverrides:移除内容结尾的匹配字符串(如多余的逗号 ,

建议使用SET和WHERE

4. foreach

        代码演示

接口为:

List<Person> findNameByAges(List<Integer> ages);
<select id="findNameByAges" resultMap="baseResultMap">
        SELECT * FROM person
        <where>
            age in
            <foreach collection="list" item="a" open="(" close=")" separator=",">
                #{a}
            </foreach>
        </where>
    </select>

如:list为{10,20,30},则sql语句为:

select * from person where ages in (10,20,30)

5. choose

6. 总结


网站公告

今日签到

点亮在社区的每一天
去签到