choose, when, otherwise标签是配套使用的标签。它就像我们java代码的if, else if, else.
唯一不同的是,when 和otherwise是在choose标签下使用。
when至少要有一个,otherwise最多只有一个。
目录
1.定义接口
/**
* 测试choose, when, otherwise
*/
List<Emp> getEmpByChoose(Emp emp);
2. 定义mapper映射文件
每个when是一个条件,只要满足了其中一种条件,则后面的when和otherwise不会执行,所以中间不需要用and 或者or 拼接。都不满足条件时候,otherwise默认是did=1.
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<!-- 一个choose标签表达了完整的 if else if else结构-->
<when test="empName!=null and empName !=''">
emp_name = #{empName}
</when>
<!-- when test: 当....的时候, 当满足....的时候, 执行标签的内容, 有一个when的标签满足之后就不会执行其他分支-->
<when test="age!=null and age !=''">
age = #{age}
</when>
<when test="sex!=null and sex !=''">
sex = #{sex}
</when>
<when test="email!=null and email !=''">
email = #{email}
</when>
<otherwise>
did=1
</otherwise>
</choose>
</where>
3. 定义测试方法
@Test
public void testGetEmpByChoose(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSqlMapper mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<Emp> emps = mapper.getEmpByChoose(new Emp(null, "张三", 23, "男", null));
System.out.println(emps);
}
4. 测试结果
我们从LOG中看出,只执行了emp_name。
select * from t_emp WHERE emp_name = ?
20:05:43:480 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 1787079037.
20:05:43:484 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Preparing: select * from t_emp WHERE emp_name = ?
20:05:43:572 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 张三(String)
20:05:43:606 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <== Total: 1
[Emp{eid=1, empName='张三', age=32, sex='男', email='123@qq.com', dept=null}]
5. 引伸:无参时候
List<Emp> emps = mapper.getEmpByChoose(new Emp(null, "", null, "", null));
5.1 结果
所有情况都不符合时候,执行otherwise里面的条件, did=1的结果。
20:13:50:555 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Preparing: select * from t_emp WHERE did=1
20:13:50:587 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters:
20:13:50:618 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <== Total: 2
[Emp{eid=1, empName='张三', age=32, sex='男', email='123@qq.com', dept=null}, Emp{eid=4, empName='赵六', age=56, sex='女', email='123456@qq.com', dept=null}]
更多推荐