复杂查询 — 动态SQL
多条件查询
普通的sql查询多条判断条件时
select * from emp
where 1=1 and ename = ? and job = ? and sal = ?
当其中一个条件为空时或者未提供会报错
mybatis提供了 if 标签
<if test="name != null">
and ename like concat("%",#{name},"%")
</if>
判断失败则不加入sql语句
实例
//map传参
List<Emp> selectByCondition1(Map<String,Object> searchMap);
//顺序传参
List<Emp> selectByCondition2(String ename,String job,Double sal);
//对象传参
List<Emp> selectByCondition3(SearchMap searchMap);
public class SearchMap {
private String name;
private String job;
private Double sal;
}
<select id="selectByCondition3" parameterType="hasmap" resultMap="empMap">
select * from emp where
<if test="ename != null">
ename like concat("%",#{ename},"%")
</if>
<if test="job != null">
and job = #{job}
</if>
<if test="sal != null">
and sal > #{sal}
</if>
</select>
<select