[Mybatis]动态SQL之SQL片段、Foreach标签

278 阅读1分钟

SQL片段

有时候,可能会将一些功能的部分抽取出来,方便复用!

1.使用SQL标签抽取公共的部分!

<sql id="if-title-author">
    <if test="title != null and title != '' and title !='null' and title !='undefine'">
        title=#{title}
    </if>
    <if test="author != null and author != '' and author !='null' and author !='undefine'">
        and author=#{author}
    </if>
</sql>

2.在需要使用的地方使用include标签引用即可!

<select id="queryBlogIf" parameterType="map" resultType="com.studymb.pojo.Blog">
    select * from blog
    <where>
       <include refid="if-title-author"></include>
    </where>
</select>

注意事项:

  • 最好基于单表来定义SQL片段!
  • 不要存在where标签

Foreach标签

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

foreach案例

<select id="方法名" resultType="类">
    select * from user where 1=1 and id in
    <foreach item="id" index="index" collection="ids"
        open="(" separator="," close=")" nullable="true">
          #{id}
    </foreach>
</select>

动态sql就是在拼接SQL语句,只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了!