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( ?, ?, ?, '男' )

 

 
原文地址:https://www.cnblogs.com/niujifei/p/15239262.html