MyBatis 之动态SQL

1. 概述

  • 动态 SQL 极大的简化了我们拼装SQL的操作;
  • MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作:
    • if
    • choose(when,otherwise)
    • trim(where(封装查询条件), set(封装修改条件))
    • foreach
// EmployeeMapper.java
public interface EmployeeMapper{

    // employee 携带了哪个字段,查询条件就带上哪个字段
    public List<Employee> getEmpsByConditionIf(Employee employee);

    // trim
    public List<Employee> getEmpsByConditionTrim(Employee employee);

    //choose
    public List<Employee> getEmpsByConditionChoose(Employee employee);

    // 修改数据库中的值
    public void updateEmp(Employee employee);

    // foreach 查询
    public List<Employee> getEmpsByConditionForeach(List<Integer> ids);

    // foreach 批量添加
    public void addEmps(@Param("emps")List<Employee> emps);

    // bind 标签
    public List<Employee> getEmpsTestInnerParameter(Employee employee);
}

// EmployeeMapper.xml
<?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="cn.itcast.mybatis.dao.EmployeeMapper">

    <!-- if: 判断
         示例一: 查询员工, 要求: employee 中携带了哪个字段,查询条件就带上哪个字段
    -->
    <select id="getEmpsByConditionIf" resultType="cn.itcast.mybatis.bean.Employee">
        select * from tbl_employee
        where

        <!--
            test="判断表达式(OGNL)"
            如果使用特殊符合,需要写成转义字符:
            &&:&amp;&amp;
            "":&quot;&quot;

            备注:
               查询的时候,如果某些条件没带,SQL 拼装可能会出现问题, 例如 id=null
            解决方法:
                1. 在 where 后面添加 1=1, 以后的条件都 and xxx
                2. mybatis 使用 where 标签来将所有的查询条件包括在内;
                   mybatis 会将 where 标签,拼装的 SQL 语句中多出来的 and 或者 or 去掉;
                   where 标签只会去掉第一个多出来的 and 或者 or, 不会去掉如下语句中的 and
                       <if test="id!=null">
                            id=#{id} and
                       </if>
                       ...(省略)
            -->
        <if test="id!=null">
            id=#{id}
        </if>
        <if test="lastName!=null and lastName!=''">
            and last_name like #{lastName}
        </if>
        <if test="email!=null and email.trim()!=''">
            and email=#{email}
        </if>
        <if test="gender==0 or gender==1">
            and gender=#{gender}
        </if>

        <!-- SQL 拼装改进方式: 使用 where 标签 -->
        <where>
            <if test="id!=null">
                id=#{id}
            </if>
            ....(同上)
        </where>
    </select>

    <!--
        trim: 自定义字符串的截取规则
            prefix="": 给 trim标签体中SQL拼串后的这个字符串添加一个前缀;
            prefixOverrides="": 去掉整个字符串前面多余的字符;
            suffix=""
            suffixOverrides=""
    -->
    <select id="getEmpsByConditionTrim" resultType="cn.itcast.mybatis.bean.Employee">
        select * from tbl_employee
        <trim prefix="where" suffixOverrides="and">
            <if test="id!=null">
                id=#{id} and
            </if>
            <if test="lastName!=null and lastName!=''">
                last_name like #{lastName} and
            </if>
            <if test="email!=null and email.trim()!=''">
                email=#{email} and
            </if>
            <if test="gender==0 or gender==1">
                gender=#{gender}
            </if>   
        </trim>     
    </select>

    <!--
        choose: 分支选择
        示例二: 如果带了 id, 就使用 id 查询; 如果带了 lastName, 就用 lastName 查询; 只会进入其中一个                                                                                          
    -->
    <select id="getEmpsByConditionChoose" resultType="cn.itcast.mybatis.bean.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>
                <otherwise>
                    gender=0
                </otherwise>
            </choose>
        </where>
    </select>

    <!--
        set: 封装修改条件
    -->
    <!-- 第一种方式: 未使用 set 标签之前,可能出现多逗号,导致查询错误 -->
    <select id="updateEmp">
        update tbl_employee
        set
        <if test="lastName!=null">
            last_name=#{lastName},
        </if>
        <if test="email!=null">
            email=#{email},
        </if>
        <if test="gender!=null">
            gender=#{gender}
        </if>
        where id=#{id}
    </select>

    <!-- 第二种方式: 使用 set 标签, 可以自动去除多余的逗号 -->
    <select id="updateEmp">
        update tbl_employee
        <set>
            <if test="lastName!=null">
                last_name=#{lastName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </set>
        where id=#{id}
    </select>

    <!-- 第三种方式: 使用 trim 标签 -->
    <select id="updateEmp">
        update tbl_employee
        <trim prefix="set" suffixOverrides=",">
            <if test="lastName!=null">
                last_name=#{lastName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </trim>
        where id=#{id}
    </select>

    <!--
        forEach:
    -->
    <!-- 使用 forEach 之前 -->
    <select id="getEmpsByConditionForeach" resultType="cn.itcast.mybatis.bean.Employee">
        select * from tbl_employee where id in(1,2,3)
    </select>

    <!-- 使用 foreach 查询 -->
    <select id="getEmpsByConditionForeach" resultType="cn.itcast.mybatis.bean.Employee">
        select * from tbl_employee where id in
        <!--
            collection: 指定要遍历的集合; (具体见"参考资料"中"Parameter...")
                list 类型的参数会封装到map中,map的key就叫 list,
                数组类型的参数,将会以 "arry" 作为键
            item: 将当前遍历出的元素赋值给指定的变量;
                  #{变量名}: 就能取出变量的值,也就是当前遍历出的元素;
            seperator: 每个元素之间的分隔符;
            open: 遍历出所有结果,拼接一个开始的字符;
            close: 遍历出所有结果,拼接一个结束的字符;
            index: 索引,遍历list 的时候,index 就是索引,item就是当前值;
                       遍历map 的时候,index 表示的就是map的key,item就是map的值;
        -->
        <foreach collection="list" item="item_id" separator="," open="(" close=")">
            #{item_id}
        </foreach>

        <!-- 第二种方式: 在参数中使用注解 @Param("指定名称")
                public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
        -->
        <foreach collection="ids" item="item_id" seperator="," open="(" close=")">
            #{item_id}
        </foreach>
    </select>

    <!-- 使用 foreach 批量保存 -->
    <!-- 第一种方式 -->
    <insert id="addEmps">
        insert into tbl_employee(last_name,email,gender,d_id)
        values
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
        </foreach>
    </insert>

    <!-- 第二种方式:
        需要更改 dbconfig.properties:
        jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
    -->
    <insert id="addEmps">
        <foreach collection="emps" item="emp" separator=";">
            insert into tbl_employee(last_name,email,gender,d_id)
            values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
        </foreach>
    </insert>

    <!-- Oracle 数据库批量保存:
        Oracle 不支持values(),(),...
        Oracle 支持的批量方式:
            1. 多个 insert 放在 begin...end 里面
                begin
                    insert into employees(employee_id,last_name,email)
                    values(employees_seq.nextval,'test001','test001@163.com');
                    insert into employees(employee_id,last_name,email)
                    values(employees_seq.nextval,'test002','test002@163.com');
                end;
            2. 利用中间表
                insert into employees(employee_id,last_name,email)
                    select employees_sql.nextval,lastName,email from(
                        select 'test_a_01' lastName,'test_a_e01' email from dual
                        union
                        select 'test_a_02' lastName,'test_a_e02' email from dual
                        union
                        select 'test_a_03' lastName,'test_a_e03' email from dual
                    )
        -->
    <!-- Oracle 批量添加第一种方式 -->
    <insert id="addEmps" databaseId="oracle">
        <foreach collection="emps" item="emp" open="begin" close="end;">
            insert into employees(employee_id,last_name,email)
            values(employees_seq.nextval,#{emp.lastName},#{emp.email});
        </foreach>
    </insert>

    <!-- Oracle 批量添加第二种方式 -->
    <insert id="addEmps" databaseId="oracle">
        insert into employees(employee_id,last_name,email)
            select employees_sql.nextval,lastName,email from(
                <foreach collection="emps" item="emp" separator="union">
                    select #{emp.lastName} lastName,#{emp.email} email from dual
                </foreach>
            )
    </insert>

    <!-- 两个内置参数:
            不只是方法传递过来的参数可以被用来判断,取值,
            mybatis 默认还有两个内置参数:
            _parameter:代表整个参数
                单个参数: _parameter 就是这个参数;
                多个参数: 参数会被封装成一个map, _parameter 就是代表这个map;

            _databaseId: 如果 mybatis-config.xml 中配置了 databaseIdProvider 标签,
                   _databaseId 就是当前数据库的别名;
    -->

    <!-- bind 标签: 可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
    <select id="getEmpsTestInnerParameter" resutlType="cn.itcast.mybatis.bean.Employee">

        <bind name="_lastName" value="'%'+lastName+'%'"/>

        <if test="_databaseId='mysql'">
            select * from tbl_employee
            <if test="_parameter!=null">
                where last_name like #{_lastName}
            </if>
        </if>
        <if ttest="_databaseId='oracle'">
            select * from employees
            <if test="_parameter!=null">
                where last_name like #{_lastName}
            </if>
        </if>
    </select>

    <!-- sql 标签: 抽取可重用的sql片段,方便后面引用
            1. sql抽取: 经常将要查询的列名,或者插入用的列名抽取处理方便引用;
            2. include 来引用已经抽取的sql;
            3. include 还可以自定义一些property, sql 标签内部就能使用自定义的属性: ${property}
     -->
    <sql id="insertColumn">
        last_name,email,gender,d_id
    </sql>

    <!-- 修改上面foreach 批量保存(mysql) -->
    <insert id="addEmps">
        insert into tbl_employee(
            <!-- include 标签: 引用外部定义的sql -->
            <include refid="insertColumn"></include>
        )
        values
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
        </foreach>
    </insert>
</mapper>

// 测试类
public class MyBatisTest{

    @Test
    public void testDynamicSql() throws IOException{
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        SqlSession openSession = sqlSessionFactory.openSession();

        try{
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            // 创建查询条件
            Employee emp = new Employee(1,"%e%",null,null);

            // 测试 if 查询
            List<Employee> list = mapper.getEmpsByConditionIf(emp);

            // 测试 trim 查询
            List<Employee> list = mapper.getEmpsByConditionTrim(emp);

            System.out.println(list);

            // 测试 set
            Employee emp = new Employee(3,"lisi",null,null);
            mapper.updateEmp(emp);
            openSession.commit();

            // 测试 foreach 查询
            List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3,4));
            for(Employee empl : list){
                System.out.println(empl);
            }

            // 测试 foreach 批量保存
            List<Employee> list = new ArrayList<>();
            list.add(new Employee(null,"lisi","lisi@163.com","1",new Department(1)));
            list.add(new Employee(null,"mike","mike@163.com","0",new Department(2)));
            mpper.addEmps(emps);
            openSession.commit();

        }finally{
            openSession.close();
        }
    }
}
1.1 <if> 查询

1.2 <where> 查询, 后面多出 and

1.3 <set> 标签使用之前,查询语句中多出逗号


参考资料

原文地址:https://www.cnblogs.com/linkworld/p/7795005.html