一、需求
將動態SQL判斷代碼塊抽取出來,組成一個SQL片段。其它的statement中就可以引用SQL片段。
二、定義SQL片段
<!-- 定義SQL片段
id:sql片段的唯一標識
經驗:是基於單表來定義SQL片段,這樣這個SQL片段的可重用性才高
在SQL片段中不要包括where
-->
<sql id="query_user_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>
</sql>
三、使用SQL片段
<!-- 用戶信息綜合查詢
#{userCustom.sex}:取出pojo包裝對象中性別值
${userCustom.username}:取出pojo包裝對象中用戶名稱
-->
<select id="findUserList" parameterType="UserQueryVo"
resultType="UserCustom">
select * from user
<!--
where可以自動去掉條件中的第一個and
-->
<where>
<!-- 引用SQL片段的id,如果refid指定的id不在本mapper文件中,
需要前邊加namespace,include標籤必須寫成單標籤或寫在一行上,
否則會報錯 -->
<include refid="query_user_where"></include>
<!-- 在這裏還要引用其他的SQL片段 -->
</where>
</select>
四、測試
運行測試中的對應方法進行測試。
/**
* 測試用戶信息的綜合查詢
* @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);
}