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