Mybatis中動態SQL多條件查詢


Mybatis中動態SQL多條件查詢

mybatis中用於實現動態SQL的元素有: if:用if實現條件的選擇,用於定義where的字句的條件。

 

choosewhen otherwise)相當於Java中的switch語句,通常whenotherwise一起使用。

 

where:簡化SQL語句中的where條件。

 

set 解決SQL語句中跟新語句

 

我們課已通過幾個例子來看一下這幾個元素的運用場景:

 

if:

 

<select id="queryEmp"  resultType="cn.test.entity.Emp">

          select * from emp where 1=1

          <if test="deptNo!=null">

          and deptno=#{deptNO}

          </if>

          <if test="deptName!=null">

          and deptno=#{deptName}

          </if>

          </select>

注:<if test="deptNo!=null">中 的deptNo是指實體類中的屬性或字段;

 

choose

 

<select id="queryEmp"  resultType="cn.test.entity.Emp">

          select * from emp where 1=1

          <choose>

          <when test="deptNo!=null">

          and deptno=#{deptNo}

          </when>

          <when test="deptName!=null">

          and deptname=#{deptName}

          </when>

          <otherwise>

          and personnum>#{personNum}

          </otherwise>

          </choose>

          </select>

注:上面也說了,choose相當於Java中的switch語句;當第一個when滿足時;就只執行第一個when中的條件。當when中的條件都不滿足時;就會執行默認的的;也就是otherwise中的語句。

 

where

 

<select id="queryEmp"  resultType="cn.test.entity.Emp">

          select * from emp

          <where>

          <if test="deptNo!=null">

          and deptno=#{deptNO}

          </if>

          <if test="deptName!=null">

          and deptno=#{deptName}

          </if>

          </where>

          </select>

 

注: where下面第一個if語句中以and開頭,也可以省略第一個and ,如果第一個if語句中有andmybatis會將第一個and忽略。

 

 

 

set

 

 

<update id="updateEmp" parameterType="cn.test.entity.Emp" flushCache="true">

          update emp

          <set>

          <if test="empName!=null">empname=#{empName},</if>

          <if test="job!=null">job=#{job}</if>

          </set>

          where empno=#{empNo}

          </update>

 

 

 

注:  在mybatis中的SQL語句結尾不能加“;”,這樣會導致mybatis無法識別字符;導致SQL語句的語法錯誤;出現 java.sql.SQLSyntaxErrorException: ORA-00911: 無效字符的錯誤。的異常。

動態SQL語句***

1<if> 習慣按null來判斷

2where a. WHERE 1=1 b<where>去掉開頭的and或者or

3set,去掉最后的逗號,沒有就不管

4foreach 遍歷,collection數組類型,item當前循環的實例,open開頭的字符串,close結尾的字符串,separator分隔符。最常用用在in子查詢串

<foreach collection="array" item="id" open="(" close=")" separator=",">

 

 


免責聲明!

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



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