1、作用
代替where关键字以及
根据传入参数情况自动去除多余的and、or关键字。
2、需求
根据 性别 查找用户
3、示例
测试
@Test
public void testWhere(){
SqlSession sqlSession = SqlSessionKit.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 用户信息(查询条件)
User user = new User();
// user.setUsername("%小%");
user.setSex("1");
List<User> users = mapper.findBy(user);
users.forEach(u -> System.out.println(u));
}
配置
<select id="findBy" resultType="com.itheima.mybatis.day03.sql.model.User">
select * from user
<where>
<if test="username !=null and username!=''">
and username like #{username}
</if>
<if test="sex !=null and sex!=''">
and sex = #{sex}
</if>
</where>
</select>
结果
DEBUG [main] - ==> Preparing: select * from user WHERE sex = ? DEBUG [main] - ==> Parameters:
1(String) DEBUG [main] - <== Total: 5 User{id=10, username='张三', birthday=Thu Jul 10 00:00:00 CST
2014, sex='1', address='北京市'} User{id=16, username='张小明', birthday=null, sex='1', address='河南郑
州'} User{id=22, username='陈小明', birthday=null, sex='1', address='河南郑州'} User{id=24,
username='张三丰', birthday=null, sex='1', address='河南郑州'} User{id=25, username='陈小明',
birthday=null, sex='1', address='河南郑州'}
4、注意
where标签无论外部有没有where关键字都会为最终sql添加where