mybatis动态SQL多条件查询2 - where 标签
上一章我们介绍了if标签,用恒成立where 1=1,可以解决where之后参数没设置或者所有参数都没设置的情况。但是这样会造成where关键字的浪费,本节我们将介绍where标签。
1.mapper接口不变
mapper接口不变,和上一章介绍的if标签中是一样的。如果不会新建文件可以查看上一章if标签的介绍。
/** * 多条件查询员工信息 */ List<Emp> getEmpByCondition(Emp emp);
2.mapper映射文件
将上一节的where 1=1恒成立已经去掉,设置Where标签,原来的if标签放在where标签的下面。
此处where标签可以帮助我们动态设置sql语句中where后跟着的内容。
<select id="getEmpByCondition" resultType="Emp"> select * from t_emp <where> <if test="empName != null and empName != "> emp_name = #{empName} </if> <if test="age != null and age != "> and age = #{age} </if> <if test="sex != null and sex != "> and sex = #{sex} </if> <if test="email != null and email != "> and email = #{email} </if> </where> </select>
3.不传入参数
传入参数条件都是null,观察后面结果中的log信息,无参数传入时候,where条件语句中的内容不会执行。
@Test public void testGetEmpByCondition(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); DynamicSqlMapper mapper = sqlSession.getMapper(DynamicSqlMapper.class); List<Emp> emps = mapper.getEmpByCondition(new Emp(null, null, null, null, null)); System.out.println(emps); }
3.1 测试结果
4. 传入参数
List<Emp> emps = mapper.getEmpByCondition(new Emp(null, null, 32, null, null));
4.1 测试结果
我们可以从LOG里看出,where标签后只执行了 age条件,并不会报错,此处where标签可以帮我们处理and sex之前的and, 而不会报错。
5. 总结
where标签
where标签有内容: 会自动生成where关键字,并且将内容前多余的and或者or去掉。
where标签没有内容: 此时where标签没有任何效果,只会执行where前的语句,如select * from t_emp