动态SQL标签

if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行

where和if一般结合使用:

  • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
  • 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉

    1. <select id="getUser2" resultMap="rmap">
    2. select * from user
    3. <where>
    4. <if test="id != null">
    5. id = #{id}
    6. </if>
    7. <if test="name != null">
    8. and name = #{name}
    9. </if>
    10. <if test="age != null">
    11. and age = #{age}
    12. </if>
    13. </where>
    14. </select>

    用来迭代任何可迭代的对象(如数组,集合)。

  • collection 属性:

    • mybatis会将数组参数,封装为一个Map集合。
      • 默认:array = 数组
    • 使用@Param注解改变map集合的默认key的名称
  • item 属性:本次迭代获取到的元素。
  • separator 属性:集合项迭代之间的分隔符。foreach 标签不会错误地添加多余的分隔符。也就是最后一次迭代不会加分隔符。
  • open 属性:该属性值是在拼接SQL语句之前拼接的语句
  • close 属性:该属性值是在拼接SQL语句拼接后拼接的语句
    1. <select id="getUserByIds" resultType="com.example.workspace.model.User">
    2. select * from user
    3. <where>
    4. <foreach collection="list" item="id" separator="," open="id in (" close=")" >
    5. #{id}
    6. </foreach>
    7. </where>
    8. </select>

  • sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

  • 引用sql片段

    1. <!--SQL片段-->
    2. <sql id="select">
    3. select * from user
    4. </sql>
    5. <select id="getUser" resultMap="rmap">
    6. <!--引用sql片段-->
    7. <include refid="select"></include>
    8. where id=#{id}
    9. </select>