动态sql:sql内容是变化的,可以根据条件获取到不同的sql语句,主要用于解决查询条件不确定。主要是where部分发生变化。
实现:使用mybatis提供的标签,<if> <where> <foreach>

标签介绍

语法:<if test=”条件”> sql 语句的部分 </if>

  1. <select id="selectStudentIf" resultType="com.liangwei.entity.Student">
  2. select id, name, email, age from student
  3. where 1=1
  4. <if test="name != null and name != '' ">
  5. and name = #{name}
  6. </if>
  7. <if test="age > 0">
  8. or age &gt; #{age}
  9. </if>
  10. </select>

where 1=1 这里是为了防止某些条件没有满足造成的sql语法错误

在有查询条件时, 可以自动添加上 where 子句;没有查询条件时,不会添加where 子句。需要注意的是,第一个标签中的 SQL 片断,可以不包含 and。不过,写上 and 也不错,系统会将多出的 and 去掉。但其它中 SQL 片断的 and,必须要求写上。否则 SQL 语句将拼接出错 。

  1. <select id="selectStudentIf" resultType="com.liangwei.entity.Student">
  2. select id, name, email, age from student
  3. <where>
  4. <if test="name != null and name != '' ">
  5. and name = #{name}
  6. </if>
  7. <if test="age > 0">
  8. or age &gt; #{age}
  9. </if>
  10. </where>
  11. </select>

标签用于实现对于数组与集合的遍历。对其使用,需要注意:

  • collection 表示要遍历的集合类型, list , array 等。
  • open、 close、 separator 为对遍历内容的 SQL 拼接。

    用法1:基本数据类型

    1. /**
    2. * foreach标签用法1
    3. * @param idlist
    4. * @return
    5. */
    6. List<Student> selectForeachOne(List<Integer> idlist);
    1. <select id="selectForeachOne" resultType="com.liangwei.entity.Student">
    2. select id, name , email, age from student where id in
    3. <foreach collection="list" item="myid" open="(" close=")" separator=",">
    4. #{myid}
    5. </foreach>
    6. </select>
  • collection:接口中方法参数的类型。

    • 数组使用 array
    • list集合使用list
  • item:自定义的,表示数组和集合成员的变量
  • open:循环开始时的字符
  • close:循环结束时的字符
  • separator:分割字符

用法2:对象

  1. /**
  2. * foreach标签用法2
  3. * @param idlist
  4. * @return
  5. */
  6. List<Student> selectForeachTwo(List<Student> stuList);
  1. <select id="selectForeachTwo" resultType="com.liangwei.entity.Student">
  2. select id, name , email, age from student
  3. <if test="list != null and list.size() > 0">
  4. where id in
  5. <foreach collection="list" item="stuObject" open="(" close=")" separator=",">
  6. #{stuObject.id}
  7. </foreach>
  8. </if>
  9. </select>

代码片段

  1. <sql id="studetnSql">
  2. select id, name, email, age from student
  3. </sql>
  4. <select id="selectStudentSqlFragment" resultType="com.liangwei.entity.Student">
  5. <include refid="studentSql"/>
  6. <if test="list != null and list.size() > 0">
  7. where id in
  8. <foreach collection="list" item="stuObject" open="(" close=")" separator=",">
  9. #{stuObject.id}
  10. </foreach>
  11. </if>
  12. </select>