MyBatis(五)動態SQL 之 choose(when、otherwise)標簽


一、choose 標簽

  choose 主要用於分支判斷,類似於 java 中帶了 break的 switch...case,只會滿足所有分支中的一個
  語法格式:
<choose>
    <when test=""> 通過test表達式拼接SQL <when test="">
    <otherwise></otherwise> 當when都不符合條件,就會選擇otherwise拼接SQL </choose>

 

  標簽說明:
<choose>:選擇某一個 when 或 otherwise 拼接 SQL
<when>:通過  test 表達式拼接 SQL;
<otherwiese>:當 when 都不符合條件,就會選擇 otherwise 拼接 SQL

  

  注意:<choose> 只會往 SQL 語句中添加一個條件(相當於帶了break的 switch...case)。

二、代碼示例

  1、在接口中聲明方法

public List<Employee> getEmpsByConditionChoose(Employee employee);

 

  2、在對應的 xml 中進行配置

    <!-- 如果帶了id就用id查,如果帶了lastName就用lastName查,只會進入其中一個 choose (when, otherwise):分支選擇,帶了break的 swtich...case -->
    <!-- public List<Employee> getEmpsByConditionChoose(Employee employee); -->
    <select id="getEmpsByConditionChoose" resultType="Employee"> select * from tbl_employee <where>
            <choose>
                <when test="id!=null"> id=#{id} </when>
                <when test="lastName!=null and lastName!=''"> last_name like #{lastName} </when>
                <when test="email!=null"> email=#{email} </when>
                <otherwise> gender = 0 </otherwise>
            </choose>
        </where>
    </select>

 

  3、運行SQL語句

select * from tbl_employee where id=?

 

    當第一個 when 成立時,后面的就不再進行拼接

select * from tbl_employee where gender=0

    當前面的 when 都不成立時,就會拼接 otherwise 中的語句。

 

 

三、使用 choose 實現添加

  添加員工時,如果性別為'男',設置為'男',如果為'女',設置為'女',其他信息設置為'不詳'

  在接口中聲明方法:

//添加員工信息,設置性別
public void insertEmpByConditionChoose(Employee employee);

 

  在對應的 xml 中配置:

     <!-- public void insertEmp(Emp emp); -->
     <insert id="insertEmp"> insert into tbl_employee(id, last_name, email, gender) values( null, #{lastName}, #{email}, <choose>
                  <when test='gender == "男"'>'男'</when>
                  <when test='gender == "女"'>'女'</when>
                  <otherwise>'不詳'</otherwise>
              </choose> ) </insert>

 

  執行的 SQL:

insert into tbl_employee(id, last_name, email, gender) values( ?, ?, ?, '不詳' )
insert into tbl_employee(id, last_name, email, gender) values( ?, ?, ?, '男' )

 

 

 

 


免責聲明!

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



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