59MyBatis - if元素(复习)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20042935/article/details/89226523

前面有讲过,可以参考:动态SQL的 if标签

在MyBatis中,元素是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择。

在实际应用中,我们可能会通过多个条件来精确地查询某个数据。
例如,要查找某个客户的信息,可以通过姓名和职业来查找客户,也可以不填写职业直接通过姓名来查找客户,还可以都不填写而查询出所有客户,此时姓名和职业就是非必须条件。
类似于这种情况,在MyBatis中就可以通过< if>元素来实现。下面就通过一个具体的案例,来演示这种情况下< if>元素的使用,具体实现步骤如下。

项目目录结构

在这里插入图片描述

修改映射文件CustomerMapper.xml

在映射文件中使用< if>元素编写根据 客户姓名职业 组合条件查询客户信息列表的动态SQL.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.CustomerMapper">
    <!——<if>元素使用 ——>
    <select id="findCustomerByNameAndJobs"
        parameterType="com.itheima.po.Customer"
        resultType="com.itheima.po.Customer">
		
		   select * from t_customer where 1=1

    		<if test="username!=null and username!=''">
        			and username like concat('%',#sername, '%')
   			 </if>

        <if test="jobs!=null and jobs!=''">
                  and jobs= #{jobs}
        </if>
	</select>
</mapper> 

上面使用< if>元素的test属性分别对username和jobs进行了非空判断(test属性多用于条件判断语句中,用于判断真假,大部分的场景中都是进行非空判断,有时候也需要判断字符串、数字和枚举等),如果传入的查询条件非空就进行动态SQL组装。

测试方法

    /**
     * 根据客户姓名和职业组合条件查询客户信息列表
     */
    @Test
    public void findCustomerByNameAndJobsTest() {
     
        // 通过工具类生成SqlSession对象
        SqlSession session = MybatisUtils.getSession();
     
        // 创建Customer对象,封装需要组合查询的条件
        Customer customer = new Customer();
        customer.setUsername("jack");
        customer.setJobs("teacher");
     
        // 执行SqlSession的查询方法,返回结果集
        List<Customer> customers = session.selectList("com.itheima.mapper"
                + ".CustomerMapper.findCustomerByNameAndJobs", customer);
     
        // 输出查询结果信息
        for (Customer customer2 : customers) {
            // 打印输出结果
            System.out.println(customer2);
        }
     
        // 关闭SqlSession
        session.close();
    }

猜你喜欢

转载自blog.csdn.net/qq_20042935/article/details/89226523