★学习目标:
掌握MyBatis中的<choose>、<when>、<otherwise>元素,能够熟练将这三个元素组合使用
★思考任务:
<choose>、<when>、<otherwise>元素的作用是什么?
★任务学习:
★知识要点:
<choose><when>otherwise>使用场景
在使用<if>元素时,只要test属性中的表达式为true,就会执行元素中的条件语句,但是在实际应用中,有时只需要从多个选项中选择一个去执行。例如下面的场景:“当客户名称不为空,则只根据客户名称进行客户筛选;当客户名称为空,而客户职业不为空,则只根据客户职业进行客户筛选。当客户名称和客户职业都为空,则要求查询出所有电话不为空的客户信息。”针对上面情况,使用<if>元素进行处理是不合适的。MyBatis提供了<choose>、<when>、<otherwise>元素进行处理,这三个元素往往组合在一起使用,作用相当于Java语言中的if…else if…else。
使用<choose>、<when>、<otherwise>元素组合去实现上面场景出现的情况。在映射文件CustomerMapper.xml中,添加使用<choose>、<when>、<otherwise>元素执行上述情况的动态SQL。
<!-- 只展示三个组合元素的部分-->
<choose>
<when test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</when>
<when test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</when>
<otherwise>and phone is not null</otherwise>
</choose>
在测试类MyBatisTest中,编写测试方法findCustomerByNameOrJobsTest(),该方法用于根据客户姓名或职业查询客户信息列表。
public void findCustomerByNameOrJobsTest() {
SqlSession session=MyBatisUtils.getSession();
Customer customer=new Customer();
customer.setUsername("tom");customer.setJobs("teacher");
List<Customer> customers=session.selectList("com.itheima.mapper"
+ ".CustomerMapper.findCustomerByNameOrJobs",customer);
for (Customer customer2 : customers) {
System.out.println(customer2);}
session.close();
}

