mybatis動態SQL if的test寫法及規則詳解

mybatis動態SQL if的test寫法

使用動態SQL最常見情景

是根據條件包含 where 子句的一部分。

比如:

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE'
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

其中 test 的表達式是基於OGNL 的表達式,語法規則也是OGNL的語法規則。

官方語法規則手冊

OGNL官方表達式手冊:https://commons.apache.org/proper/commons-ognl/language-guide.html

舉個例子

在這裡插入圖片描述

上圖是官方指導的一部分,主要說明瞭,在test中無法使用<= 等符號可以使用 lte 代替。

運算符 代替字符
< lt
<= lte
> gt
>= gte

mybatis if test動態sql語句

<select id="getStudentId" parameterType="java.lang.String" resultType="java.lang.String">
        SELECT MAX(Student_ID) FROM Student
        <where>
            <if test="classid !=null and classid !=''">  
                AND CLASS_ID = {student.classID} 
            </if>
            <if test="age ==null or age ==''">  
                AND AGE = {student.age}
            </if>
        </where>
</select>

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: