Mybatis的动态SQL

今天,主要学习 MyBatis 的动态 SQL。这是 MyBatis 的强大特性之一。

动态 SQL 的作用

MyBatis 的动态 SQL 主要就是为了解决手动拼接 SQL 的麻烦

动态 SQL 中的元素

动态 SQL 是 MyBatis 的强大特性之一,MyBatis3 采用了功能强大的基于 OGNL 的表达式来完成动态 SQL。动态 SQL 主要元素如下表所示:

1.<if> 元素

在 MyBatis 中,<if> 元素是最常用的判断语句,它类似于 Java 中的 if 语句,主要用于实现某些简单的条件选择。其基本使用示例如下:

    <select id="findCustomerByNameAndJobs" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
        select * from t_customer where 1=1
        <if test="username != null and username !=''">
            and username like '%${username}%'
        </if>
        <if test="jobs != null and jobs !=''">
            and jobs = #{jobs}
        </if>
    </select>

2.<choose>、<when>、<otherwise> 元素

如果是 java 语言,这种情况就相当于 switch...case...default 语句。

      select * from t_customer where 1=1
      <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>

3. <where>、<trim> 元素

在前面案例中,映射文件中编写的 SQL 后面都加入了“where 1=1”的条件,那么到底为什么要这么写呢?如果将 where 后“1=1”的条件去掉,那么 MyBatis 所拼接出来的 SQL 将会如下所示

select * from t_customer where and username like '%'? '%'

可以看出上面 SQL 语句明显存在 SQL 语法错误,而加入了条件“1=1”后,既保证了 where 后面的条件成立,又避免了 where 后面第一个词是 and 或者 or 之类的关键词。
不过“where 1=1”这种写法对于初学者来将不容易理解,并且也不够雅观。
针对上述情况中“where 1=1”,在 MyBatis 的 SQL 中就可以使用或元素进行动态处理。

      select * from t_customer
      <where>
           <if test="username !=null and username !=''">
                 and username like concat('%',#{username}, '%')
           </if>
           <if test="jobs !=null and jobs !=''">
                 and jobs= #{jobs}
           </if>
      </where>

上述代码中,使用 <where> 元素对“where 1=1”条件进行了替换,<where> 元素会自动判断组合条件下拼装的 SQL 语句,只有 <where> 内的条件成立时,才会在拼接 SQL 中加入 where 关键字,否则将不会添加;
即使 where 之后的内容有多余的“AND”或“OR”,<where> 元素也会自动将它们去除。

    select * from t_customer
         <trim prefix="where" prefixOverrides="and">
                <if test="username !=null and username !=''">
                      and username like concat('%',#{username}, '%')
                </if>
                <if test="jobs !=null and jobs !=''">
                      and jobs= #{jobs}
                </if>
         </trim>

<trim> 的作用是去除特殊的字符串,它的 prefix 属性代表语句的前缀,prefixOverrides 属性代表需要去除的哪些特殊字符串,功能和 <where> 基本是等效的。

4.<set> 元素

在 Hibernate 中,想要更新某个对象,就需要发送所有的字段给持久化对象,这种想更新的每一条数据都要将其所有的属性都更新一遍的方法,其执行效率是非常差的。为此,在 MyBatis 中可以使用动态 SQL 中的 <set> 元素进行处理:

<update id="updateCustomer"  parameterType="com.itheima.po.Customer">
        update t_customer 
        <set>
            <if test="username !=null and username !=''">
                  username=#{username},
            </if>
            <if test="jobs !=null and jobs !=''">
                  jobs=#{jobs},
            </if>
        </set>
        where id=#{id}
</update>

上述配置中,使用了 <set> 和 <if> 元素结合来组装 update 语句。其中 <set> 元素会动态前置 SET 关键字,同时也会消除 SQL 语句中最后一个多余的逗号;
<if> 元素用于判断相应的字段是否为空,如果不为空,就将此字段进行动态 SQL 组装,并更新此字段,否则不执行更新。

5.<foreach> 元素

<foreach> 元素是一个循环语句,它的作用是遍历集合,它能够很好地支持数组和 List、Set 接口的集合,对此提供遍历功能。它往往用于 SQL 中的 in 关键字。其基本使用示例如下所示:

    <select id="findCustomerByIds" parameterType="List"
                         resultType="com.itheima.po.Customer">
           select * from t_customer where id in
            -- 判断为空可以用 list.size>0
            <foreach item="id" index="index" collection="list" 
                            open="(" separator="," close=")">
                   #{id}
            </foreach>
     </select>

关于上述示例中元素中使用的几种属性的描述具体如下:

  • item:配置的是循环中当前的元素。

  • index:配置的是当前元素在集合的位置下标。

  • collection:配置的 list 是传递过来的参数类型(首字母小写),它可以是一个 array、list(或 collection)、Map 集合的键、POJO 包装类中数组或集合类型的属性名等。

  • open 和 close:配置的是以什么符号将这些集合元素包装起来。

  • separator:配置的是各个元素的间隔符。

注意:
在使用 <foreach> 时最关键也是最容易出错的就是 collection 属性,该属性是必须指定的,而且在不同情况下,该属性的值是不一样的。主要有以下 3 种情况:
1. 如果传入的是单参数且参数类型是一个数组或者 List 的时候,collection 属性值分别为 array 和 list(或 collection)。

2. 如果传入的参数是多个的时候,就需要把它们封装成一个 Map 了,当然单参数也可以封装成 Map 集合,这时候 collection 属性值就为 Map 的键。

3. 如果传入的参数是 POJO 包装类的时候,collection 属性值就为该包装类中需要进行遍历的数组或集合的属性名。

6.<bind> 元素

首先,看一下这条 sql:

select * from t_customer where username like '%${value}%'

1. 如果使用“${}”进行字符串拼接,则无法防止 SQL 注入问题;

2. 如果改用 concat 函数进行拼接,则只针对 MySQL 数据库有效;

3. 如果改用“||”进行字符串拼接,则只针对 Oracle 数据库有效。

这样,映射文件中的 SQL 就要根据不同的情况提供不同形式的实现,这显然是比较麻烦的,且不利于项目的移植。为了减少这种麻烦,就可以使用 MyBatis 的元素来解决这一问题。

MyBatis 的元素可以通过 OGNL 表达式来创建一个上下文变量,其使用方式如下:

     <select id="findCustomerByName" parameterType="com.itheima.po.Customer"
                 resultType="com.itheima.po.Customer">
            <!--_parameter.getUsername() 表示传递进来的参数(也可以直接写成对应的参数变量名,如 username)-->
          <bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'" />
           select * from t_customer 
           where 
            <!-- 需要的地方直接引用 <bind> 元素的 name 属性值即可 -->
           username like #{pattern_username}
     </select>

案例

开发工具:idea
Java 环境: jdk1.8.0_121
数据库:SQLServer
项目结构:

jar 包:

实体类 Customer

public class Customer {
    private Integer id;             // 主键
    private String username;        // 客户名称
    private String jobs;            // 职业
    private String phone;           // 电话
    // 省略 setter 和 getter 方法
}

CustomerMapper.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">
    <span class="hljs-comment">&lt;!--namespace表示命名空间--&gt;</span>

<mapper namespace="com.ma.mapper.CustomerMapper">

<span class="hljs-comment">&lt;!--if元素使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByNameAndJobs"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    select * from t_customer where 1=1
    <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username != ''"</span>&gt;</span>
        and username like '%${username}%'
    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs !=''"</span>&gt;</span>
        and jobs = #{jobs}
    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-comment">&lt;!--choose when otherwise使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByNameOrJobs"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    select * from t_customer where 1=1
    <span class="hljs-tag">&lt;<span class="hljs-name">choose</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username !=''"</span>&gt;</span>
            and username like '%${username}%'
        <span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">when</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs != ''"</span>&gt;</span>
            and jobs = #{jobs}
        <span class="hljs-tag">&lt;/<span class="hljs-name">when</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">otherwise</span>&gt;</span>
            and phone is not null
        <span class="hljs-tag">&lt;/<span class="hljs-name">otherwise</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">choose</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

<span class="hljs-comment">&lt;!--where trim 使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByNameAndJobs1"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    select * from t_customer
    <span class="hljs-tag">&lt;<span class="hljs-name">where</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username != ''"</span>&gt;</span>
            and username like '%${username}%'
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs !=''"</span>&gt;</span>
            and jobs = #{jobs}
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">where</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-comment">&lt;!--where trim 使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByNameAndJobs2"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    select * from t_customer
    <span class="hljs-tag">&lt;<span class="hljs-name">trim</span> <span class="hljs-attr">prefix</span>=<span class="hljs-string">"where"</span> <span class="hljs-attr">prefixOverrides</span>=<span class="hljs-string">"and"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username != ''"</span>&gt;</span>
            and username like '%${username}%'
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs !=''"</span>&gt;</span>
            and jobs = #{jobs}
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">trim</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username != ''"</span>&gt;</span>
        and username like '%${username}%'
    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs !=''"</span>&gt;</span>
        and jobs = #{jobs}
    <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

<span class="hljs-comment">&lt;!--set使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">update</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"updateCustomer"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    update t_customer
    <span class="hljs-tag">&lt;<span class="hljs-name">set</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"username != null and username != ''"</span>&gt;</span>
            username = #{username}
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"jobs != null and jobs != ''"</span>&gt;</span>
            jobs = #{jobs}
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">"phone != null and phone != ''"</span>&gt;</span>
            phone = #{phone},
        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">set</span>&gt;</span>
    where id = #{id}
<span class="hljs-tag">&lt;/<span class="hljs-name">update</span>&gt;</span>

<span class="hljs-comment">&lt;!--foreach元素使用--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByIds"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"List"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    select * from t_customer where id in
    <span class="hljs-tag">&lt;<span class="hljs-name">foreach</span> <span class="hljs-attr">item</span>=<span class="hljs-string">"id"</span> <span class="hljs-attr">collection</span>=<span class="hljs-string">"list"</span> <span class="hljs-attr">open</span>=<span class="hljs-string">"("</span> <span class="hljs-attr">separator</span>=<span class="hljs-string">","</span> <span class="hljs-attr">close</span>=<span class="hljs-string">")"</span>&gt;</span>
        #{id}
    <span class="hljs-tag">&lt;/<span class="hljs-name">foreach</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-comment">&lt;!--bind元素使用,根据客户名模糊查询信息--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerByName"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"com.ma.po.Customer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"com.ma.po.Customer"</span>&gt;</span>
    <span class="hljs-comment">&lt;!--_parameter.getUsername()也可以直接写成传入的字段属性名,即username--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bind</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"pattern_username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"'%'+_parameter.getUsername()+'%'"</span>/&gt;</span>
    select * from t_customer
    where
    username like #{pattern_username}
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

</mapper>

MybatisTest

package com.ma.test;

import com.ma.po.Customer;
import com.ma.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**

  • @author mz

  • @version V1.0

  • @Description: Mybatis 测试

  • @create 2017-11-01 15:20
    */
    public class MybatisTest {

    /**

    • 根据姓名和职业查询客户 if
      */
      @Test
      public void findCustomerByNameAndJobsTest() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setUsername("jack");
      customer.setJobs("teacher");
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs", customer);
      // 输出结果
      for (Customer customer1 : customers) {
      System.out.println(customer1);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }

    /**

    • 根据客户名或职业查询客户信息 choose when otherwise
      /
      @Test
      public void findCustomerByNameOrJobsTest() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setUsername("jack");
      customer.setJobs("teacher");
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer> list = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameOrJobs", customer);
      for (Customer customer1 : list) {
      System.out.println(customer1);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }
      /
      *
    • 根据姓名和职业查询客户 where
      /
      @Test
      public void findCustomerByNameAndJobs1Test() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setUsername("jack");
      customer.setJobs("teacher");
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs1", customer);
      // 输出结果
      for (Customer customer1 : customers) {
      System.out.println(customer1);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }
      /
      *
    • 根据姓名和职业查询客户 trim
      */
      @Test
      public void findCustomerByNameAndJobs2Test() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setUsername("jack");
      customer.setJobs("teacher");
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs2", customer);
      // 输出结果
      for (Customer customer1 : customers) {
      System.out.println(customer1);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }

    /**

    • 更新数据,set 测试
      */
      @Test
      public void updateCustomerTest() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setId(3);
      customer.setPhone("1254587855");
      // 执行 SqlSession 的查询方法,返回影响行数
      int rows = sqlSession.update("com.ma.mapper.CustomerMapper.updateCustomer", customer);

      if (rows > 0) {
      System.out.println("修改了"+ rows +"条数据!");
      } else {
      System.out.println("failed");
      }
      // 提交事务
      sqlSession.commit();
      // 关闭 SqlSession
      sqlSession.close();
      }

    /**

    • foreach 测试
      */
      @Test
      public void findCustomerByIdsTest() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 List 集合,封装查询 id
      List<Integer> ids = new ArrayList<>();
      ids.add(1);
      ids.add(2);
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer> customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByIds", ids);

      for (Customer customer : customers) {
      System.out.println(customer);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }

    /**

    • 模糊查询 bind
      */
      @Test
      public void findCustomerByNameTest() {
      // 获取 SqlSession
      SqlSession sqlSession = MybatisUtils.getSession();
      // 创建 Customer 对象,封装需要组合查询的条件
      Customer customer = new Customer();
      customer.setUsername("j");
      // 执行 SqlSession 的查询方法,返回结果集
      List<Customer> customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByName", customer);
      for (Customer customer1 : customers) {
      System.out.println(customer1);
      }
      // 关闭 SqlSession
      sqlSession.close();
      }
      }

部分运行结果

小结

首先对 MyBatis 框架的动态 SQL 元素作了简要了解,然后分别对这些主要的动态 SQL 元素进行了详细说明。
通过学习可以了解常用动态 SQL 元素的主要作用,并能够掌握这些元素在实际开发中如何使用。
在 MyBatis 框架中,这些动态 SQL 元素的使用十分重要,熟练的掌握它们能够极大的提高开发效率。
以上内容是根据Java EE 企业级应用开发教程(Spring+Spring MVC+MyBatis)做的一些笔记和总结。