MyBatis-动态SQL

发布于:2025-04-17 ⋅ 阅读:(87) ⋅ 点赞:(0)

MyBatis Plus 作为 MyBatis 的增强工具,简化了 CRUD 操作,但在复杂查询时,仍需使用 MyBatis 的动态 SQL 功能。以下是一些常用的动态标签、用法示例及注意事项:

常用动态标签及用法示例

  1. <if> 标签
  • 用途:条件判断,满足条件时包含 SQL 片段。
  • 示例:
<select id="findUser" resultType="User">
    SELECT * FROM sys_user
    WHERE 1=1
# WHERE 1=1是避免条件不成立时拼接上 where 和条件成立时拼接上 AND,可以用 <where> 标签代替优化
    <if test="name != null">
        AND name = #{name}
    </if>
</select>
  1. <choose>、<when>、<otherwise> 标签
  • 用途:多条件分支(功能类似于 switch-case)。
  • 示例:
<select id="findUser" resultType="User">
    SELECT * FROM sys_user
    <where>
        <choose>
            <when test="name != null">AND name = #{name}</when>
            <when test="email != null">AND email = #{email}</when>
            <otherwise>AND is_active = 1</otherwise>
        </choose>
    </where>
</select>
  1. <foreach> 标签
  • 用途:遍历集合(如 IN 查询、批量插入)。
  • 属性:
    collection:集合参数名。
    item:遍历元素的变量名。
    open/close:包裹结果的前缀/后缀。
    separator:元素间的分隔符。
  1. 示例:
<!-- IN 查询 -->
SELECT * FROM sys_user WHERE id IN
<foreach item="id" collection="ids" open="(" separator="," close=")">
    #{id}
</foreach>
  1. <trim> 标签
  • 用途:自定义字符串修剪(可替代 <where> 或 <set> 标签)。
  • 属性:
    prefix:添加前缀。
    prefixOverrides:去除首部匹配的字符。
    suffix:添加后缀。
    suffixOverrides:去除尾部匹配的字符。
  • 示例:
<!-- 替代 <where> -->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
    <if test="name != null and name != ''">
        AND name = #{name}
    </if>
</trim>
  1. <where> 标签
  • 用途:自动添加 WHERE 关键字,并去除首条多余的 AND 或 OR。
  • 示例:
<select id="selectByUsers" resultMap="BaseResultMap" parameterType="com.xxx.entity.User">
    select
    <include refid="Base_Column_List" />
    from sys_user
    <where>
        <include refid="user-where-conditions" />
    </where>
</select>

# sql片段
<sql id="Base_Column_List">
    id, name, sex, age, email, create_time, update_time
</sql>

# sql片段 不要将<where> <set>标签放入sql片段中,否则自动处理AND和OR机制会失效
<sql id="user-where-conditions">
    <if test="name != null and name != ''">
        and name like concat('%', #{name}, '%')
    </if>
    <if test="sex != null">
        and sex = #{sex}
    </if>
</sql>
  1. <set> 标签
  • 用途:主要用于 SQL 的 UPDATE 命令中,自动添加 SET 关键字,并去除末尾多余的逗号。
  • 示例:
<update id="updateUser">
    UPDATE sys_user
    <set>
        <if test="name != null">name = #{name},</if>
        <if test="age != null">age = #{age},</if>
    </set>
    WHERE id = #{id}
</update>

注意事项

  1. <where> 和 <set> 标签:必须放在主 SQL 语句中,不能放到 SQL 片段中,以免破坏 SQL 的逻辑。
  2. <foreach> 标签:在使用前最好加上 标签判断列表是否为 null 或者有数据,否则可能会报错。
  3. <trim> 标签:正确设置 prefixOverrides 和 suffixOverrides 属性,以避免 SQL 语法错误。
  4. <choose> 标签:类似于 switch 语句,但只能有一个 <otherwise> 标签,且 <otherwise> 标签必须放在最后。
  5. 性能问题:在使用动态 SQL 时,要注意性能问题,尤其是当条件较多时,应尽量避免生成过于复杂的 SQL 语句

网站公告

今日签到

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