MyBatis的动态SQL语法

67 阅读1分钟

MyBatis的动态SQL语法允许在XML映射文件中根据不同的条件生成不同的SQL语句,这样可以在不同的情况下动态构建SQL语句,提高灵活性。以下是MyBatis中动态SQL的主要语法元素:

1. <if> 元素:

<select id="getUser" parameterType="map" resultType="User">
  SELECT * FROM user
  WHERE
  <if test="username != null">
    AND username = #{username}
  </if>
  <if test="email != null">
    AND email = #{email}
  </if>
</select>

在上面的例子中,<if> 元素用于判断条件是否成立,如果条件成立,则包含在SQL语句中。

2. <choose><when><otherwise> 元素:

<select id="getUser" parameterType="map" resultType="User">
  SELECT * FROM user
  <where>
    <choose>
      <when test="username != null">
        AND username = #{username}
      </when>
      <when test="email != null">
        AND email = #{email}
      </when>
      <otherwise>
        AND status = 'ACTIVE'
      </otherwise>
    </choose>
  </where>
</select>

<choose> 元素用于在多个条件中选择一个,<when> 用于定义条件分支,<otherwise> 用于定义默认分支。

3. <trim> 元素:

<select id="getUser" parameterType="map" resultType="User">
  SELECT * FROM user
  <trim prefix="WHERE" prefixOverrides="AND | OR">
    <if test="username != null">
      AND username = #{username}
    </if>
    <if test="email != null">
      AND email = #{email}
    </if>
  </trim>
</select>

<trim> 元素可以用于去除 SQL 语句中的多余的前缀和后缀,prefix 属性用于添加前缀,prefixOverrides 属性用于去除指定的前缀。

4. <foreach> 元素:

<select id="getUsers" parameterType="map" resultType="User">
  SELECT * FROM user
  WHERE id IN
  <foreach item="id" collection="ids" open="(" separator="," close=")">
    #{id}
  </foreach>
</select>

<foreach> 元素用于循环遍历集合,并将集合中的元素应用到SQL语句中。item 属性表示集合中的元素,collection 属性表示集合对象,open 属性表示循环开始时的字符,separator 属性表示元素之间的分隔符,close 属性表示循环结束时的字符。

这些是MyBatis中动态SQL的主要语法元素,它们可以组合使用以构建复杂的动态SQL语句。根据具体的需求,可以选择不同的动态SQL语法来构建灵活的SQL查询。