MyBatis 动态SQL

作用:简化sql语句动态拼串操作

if标签

  1. 根据需求拼接sql查询 <br /> test:判断的表达式<br />**![](https://cdn.nlark.com/yuque/0/2021/png/12987358/1617533803069-4486f4fc-ce1a-4642-b9bc-5b60a48fff51.png#align=left&display=inline&height=345&margin=%5Bobject%20Object%5D&originHeight=345&originWidth=1102&status=done&style=none&width=728)**

MyBatis 动态SQL - 图1


where标签

  1. 通过上面的例子可以看到,如果最后一个的值没有成立,倒数第二个的sql语句会多出一个and,导致报错<br /> 所以有了where标签,把if标签的内容放在where标签中,他可以帮我们去除条件不成立所导致的多余的条件(andor等等)
  1. <where>
  2. <if test="id!=null">
  3. id>#{id}
  4. </if>
  5. <if test="name!=null and !name.equals('');">
  6. and name like #{name}
  7. </if>
  8. </where>

trim标签

  1. 截取字符串<br /> prefix="",前缀;为我们下面的sql整体添加一个前缀<br /> prefixOverrides="",去除整体字符串前面多余的字符<br /> suffix="",为整体添加一个后缀<br /> suffixOverrides="",后面那个多了可以去掉
  1. <trim prefix="where" prefixOverrides="and" suffixOverrides="and">
  2. <where>
  3. <if test="id!=null">
  4. id>#{id}
  5. </if>
  6. <if test="name!=null and !name.equals('');">
  7. and name like #{name}
  8. </if>
  9. </where>
  10. </trim>

foreach标签

  1. 遍历集合<br /> collection="",指定要遍历的集合的key<br /> close="",以什么结束<br /> index="i",索引<br /> 如果遍历的是一个list;<br /> index:指定的变量保存了当前的索引<br /> item:保存当前遍历的元素的值<br /> 如果遍历的是一个map:<br /> index:指定的变量就是保存了当前遍历的元素key<br /> item:就是保存当前遍历的元素的值<br /> item="",每次遍历出的元素起一个变量名方便引用<br /> open="",以什么开始<br /> separator="",每次遍历的元素的分隔符
  1. <select>
  2. select * from user where id in
  3. <!--
  4. (#{id_item},#{id_item},#{id_item})
  5. select * from user where id in (1,3,5)
  6. -->
  7. <foreach collection="ids" item="id_item" separator="," open="(" close=")">
  8. #{id_item}
  9. </foreach>
  10. </select>

choose标签

  1. 相当于if else
  1. <select>
  2. select * from user
  3. <where>
  4. <choose>
  5. <when test="id!=null">
  6. id=#{id}
  7. </when>
  8. <when test="name!==null and !name.equals('')">
  9. name=#{name}
  10. </when>
  11. <when test="birthday!=null">
  12. birthday=#{birthday}
  13. </when>
  14. <otherwise>
  15. 1=1
  16. </otherwise>
  17. </choose>
  18. </where>
  19. </select>

set标签

  1. 动态修改字段,不用全字段更新
  1. <update>
  2. update user
  3. <set>
  4. <if test="name!=null and !name.equals('')">
  5. name=#{name},
  6. </if>
  7. <if test="birthday!=null and !birthday.equals('')">
  8. birthday=#{birthday},
  9. </if>
  10. <if test="address!=null and !address.equals('')">
  11. address=#{address}
  12. </if>
  13. </set>
  14. </update>