Mybatis if 標籤可用在許多類型的 SQL 語句中,我們以查詢為例。首先看一個很普通的查詢:
<!-- 查詢用戶列表,like用戶名稱 -->
<select id="getUserListLikeName" parameterType="User" resultMap="userResultMap">
SELECT * from user u
WHERE u.username LIKE CONCAT(CONCAT('%', #{username}),'%')
</select>
但是當 username 或 sex 為 null 時,此語句很可能報錯或查詢結果為空。此時我們使用 if 動態 sql 語句先進行判斷,如果值為 null 或等於空字元串,我們就不進行此條件的判斷,增加靈活性。
參數為實體類:User。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。
<!-- 添加 if(判斷參數) - 將實體類 User 不為空的屬性作為 where 條件 -->
<select id="getUserList" resultMap="resultMap_User" parameterType="com.zaixian.pojo.User">
SELECT u.username,
u.password,
u.sex,
u.birthday,
u.photo,
u.score,
u.sign
FROM user u
WHERE
<if test="username !=null ">
u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')
</if>
<if test="sex!= null and sex != '' ">
AND u.sex = #{Sex, jdbcType=INTEGER}
</if>
<if test="birthday != null ">
AND u.birthday = #{birthday, jdbcType=DATE}
</if>
<if test="userId != null and userId != '' ">
AND id.user_id = #{userId, jdbcType=VARCHAR}
</if>
</select>
使用時比較靈活,創建新的一個這樣的實體類,我們需要限制那個條件,只需要附上相應的值就會 where 這個條件,相反不去賦值就可以不在 where 中判斷。
public void select_by_if() {
User user = new User();
user.setUsername("");
user.setSex(1);
user.setBirthday(DateUtil.parse("1990-08-18"));
List<User> userList = this.dynamicSqlMapper.getUserList_if(user);
for (user u : userList) {
System.out.println(u.toString());
}
}
我們再看看一下另一個示例,先來看看下麵的代碼:
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</select>
這條語句的意思非常簡單,如果提供了 title 參數,那麼就要滿足 title=#{title},同樣如果提供了 Content 和 Owner 的時候,它們也需要滿足相應的條件,之後就是返回滿足這些條件的所有 Blog,這是非常有用的一個功能,以往我們使用其他類型框架或者直接使用 JDBC 的時候, 如果我們要達到同樣的選擇效果的時候,我們就需要拼 SQL 語句,這是極其麻煩的,比起來,上述的動態SQL就比較簡單了。
上一篇:
MyBatis動態SQL語句
下一篇:
MyBatis where標籤語句
