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