五、Mybatis动态SQL

<if>标签:

  根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不为空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

 1 <select id="findByCondition" parameterType="user" resultType="user">
 2 select * from User
 3     <where>
 4         <if test="id!=0">
 5         and id=#{id}
 6         </if>
 7         <if test="username!=null">
 8         and username=#{username}
 9         </if>
10     </where>
11 </select>

<foreach>标签:

  循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。传入的参数得是数组或者集合

1 <select id="findByIds" parameterType="list" resultType="user">
2   select * from User
3     <where>
4         <foreach collection="array" open="id in(" close=")" item="id" separator=",">
5       #{id}
6         </foreach>
7     </where>
8 </select>

控制台输出为:

select * from User where id in (?,?);

foreach标签的属性含义如下:
<foreach>标签用于遍历集合,它的属性:
  • collection:代表要遍历的集合元素,注意编写时不要写#{}
  • open:代表语句的开始部分
  • close:代表结束部分
  • item:代表遍历集合的每个元素,生成的变量名
  • sperator:代表分隔符

原文地址:https://www.cnblogs.com/elian91/p/15356764.html