鍍金池/ 教程/ Java/ mybaits if標(biāo)簽語句
Mybatis表關(guān)聯(lián)多對一
MyBatis打印輸出SQL語句
Mybatis表關(guān)聯(lián)一對多
mybaits if標(biāo)簽語句
MyBatis整合Spring MVC
MyBatis動態(tài)SQL語句
MyBatis教程
MyBatis choose(when, otherwise)標(biāo)簽
Mybatis與Spring集成
MyBatis分頁
MyBatis SqlSessionDaoSupport實例
MyBatis where標(biāo)簽語句
Mybatis增刪改查(CURD)
Mybatis接口注解
Mybatis trim標(biāo)簽
Mybatis set標(biāo)簽
Mybatis 多對多
MyBatis環(huán)境配置及入門

mybaits if標(biāo)簽語句

Mybatis if 標(biāo)簽可用在許多類型的 SQL 語句中,我們以查詢?yōu)槔?。首先看一個很普通的查詢:

<!-- 查詢用戶列表,like用戶名稱 -->  
<select id="getUserListLikeName" parameterType="User" resultMap="userResultMap">  
    SELECT * from user u   
WHERE u.username LIKE CONCAT(CONCAT('%', #{username}),'%')  
</select>  

但是當(dāng) username 或 sex 為 null 時,此語句很可能報錯或查詢結(jié)果為空。此時我們使用 if 動態(tài) sql 語句先進行判斷,如果值為 null 或等于空字符串,我們就不進行此條件的判斷,增加靈活性。

參數(shù)為實體類:User。將實體類中所有的屬性均進行判斷,如果不為空則執(zhí)行判斷條件。

<!-- 添加 if(判斷參數(shù)) - 將實體類 User 不為空的屬性作為 where 條件 -->  
<select id="getUserList" resultMap="resultMap_User" parameterType="com.yiibai.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> 

使用時比較靈活,創(chuàng)建新的一個這樣的實體類,我們需要限制那個條件,只需要附上相應(yīng)的值就會 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 參數(shù),那么就要滿足 title=#{title},同樣如果提供了 Content 和 Owner 的時候,它們也需要滿足相應(yīng)的條件,之后就是返回滿足這些條件的所有 Blog,這是非常有用的一個功能,以往我們使用其他類型框架或者直接使用 JDBC 的時候, 如果我們要達到同樣的選擇效果的時候,我們就需要拼 SQL 語句,這是極其麻煩的,比起來,上述的動態(tài)SQL就比較簡單了。