MyBatis動態Sql之if標簽的用法詳解


 <!--if 標簽使用類似html的C標簽的if -->
    <select id="selectUseIf" parameterType="com.soft.test.model.User" resultMap="userMap">
        select * from t_user where
        <if test="id != null and id != ''">
            id=#{id}
        </if>
        <if test="username != null and username != ''">
            and username like concat('%',#{username},'%')
        </if>
        <if test="password != null and password != ''">
            and password=#{password}
        </if>
    </select>

配置完成。現在運行測試即可看到運行的sql語句
------------------------------------------------------------------------------------------------------------------------------

DEBUG [main] - ==>  Preparing: select * from t_user where id=? and username like concat('%',?,'%') 
DEBUG [main] - ==> Parameters: 28(Integer), xiao(String)
DEBUG [main] - <==      Total: 1

-------------------------------------------------------------------------------------------------------------------------------

mybatis的if判斷語句其實跟el表達式的if條件判斷有些類似。

例如: <if test="id != null"> </if>

1 如果參數為數字類型的時候沒有特俗需求的情況只需要判斷是否為null即可。

例如:<if test="id != null"></if>

 如果有特俗需求,例如判斷是否大於某個數的時候才行。只需要加上對應的條件判斷即可

例如:<if test='id != null and id > 28'></if>

 mybatis對於這種大於小於等等還有另一種形式。

例如:<if test='id != null and id gt 28'></if>

對應關系:

---------------------------------------

    gt            對應             >

    gte         對應              >=

    lt             對應              <(會報錯  相關聯的 "test" 屬性值不能包含 '<' 字符)

    lte          對應               <=(會報錯  相關聯的 "test" 屬性值不能包含 '<' 字符)

---------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM