Mybatis动态SQL核心:对SQL语句进行灵活操作,通过表达式进行判断,对SQL进行灵活拼接、组装。
一、if判断
1.1、需求
用户信息综合查询列表和用户信息查询列表总数这两个statement的定义使用动态SQL。
1.2、修改UserMapper.xml中的SQL语句
<!-- 用户信息综合查询
#{userCustom.sex}:取出pojo包装对象中性别值
${userCustom.username}:取出pojo包装对象中用户名称
-->
<select id="findUserList" parameterType="UserQueryVo"
resultType="UserCustom">
select * from user
<!--
where可以自动去掉条件中的第一个and
-->
<where>
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</where>
</select>
<!-- 用户信息综合查询总数
parameterType:指定输入类型和findUserList一样
resultType:输出结果类型
-->
<select id="findUserCount" parameterType="UserQueryVo" resultType="int">
select count(*) from user
<!--
where可以自动去掉条件中的第一个and
-->
<where>
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</where>
</select>
1.3、修改测试代码进行测试
将测试代码中的userCustom去掉进行测试。
/**
* 测试用户信息的综合查询
* @throws Exception
*/
@Test
public void testFindUserList() throws Exception{
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建UserMapper对象,mybatis自动生成mapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//组装查询条件
UserCustom userCustom = new UserCustom();
// userCustom.setSex("1");
// userCustom.setUsername("张");
//创建包装对象,设置查询条件
UserQueryVo userQueryVo = new UserQueryVo();
userQueryVo.setUserCustom(null);
//调用userMapper方法
List<UserCustom> users = userMapper.findUserList(userQueryVo);
System.out.println(users);
}
生成的SQL语句:
select * from user