1. 动态sql
根据 name和 sex 来查询数据。如果name为空,那么将只根据sex来查询;反之只根据name来查询
SELECT id,name,sex from student where 1=1
<!--如果test为真会输出中间的内容-->
<if test="name!=null and name!=''">
and name=#{name}
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex}
</if>
</select>
where条件
where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们去除。
SELECT id,name,sex from student
<!--1、如果两个if只要有一个有输出就会在sql中添加 where-->
<where>
<if test="name!=null and name!=''">
<!--2、如果where后以and或or开始则会删除and或or-->
and name like concat(concat('%',#{name}),'%');
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex}
</if>
</where>
</select>
choose(when,otherwise) 开关
如果不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句。
假定这里需要优先根据编号搜索,没有时选择name,最后考虑sex:
接口:
复制代码
/**
* 根据学生编号、姓名和性别获得学生集合
*/
List selectStudentsByNameAndSex(@Param(“id”) int id, @Param(“name”) String name,@Param(“sex”) String sex);
复制代码
映射:
复制代码
SELECT id,name,sex from student
<where>
<choose>
<when test="id>0">
id=#{id}
</when>
<when test="name!=null and name!=''">
name=#{name}
</when>
<otherwise>
sex=#{sex}
</otherwise>
</choose>
</where>
</select>