一. MyBatis 简介

概述

MyBatis 是一个优秀的基于 Java 的持久层框架,它内部封装了 JDBC,使开发者只需关注 SQL 语句本身,而不用再花费精力去处理诸如注册驱动、创建 Connection、配置 Statement 等繁杂过程。
Mybatis 通过 xml 或注解的方式将要执行的各种 Statement(Statement、PreparedStatement 等)配置起来,并通过 Java 对象和 Statement 中 SQL 的动态参数进行映射生成最终执行的 SQL 语句,最后由 MyBatis 框架执行 SQL 并将结果映射成 Java 对象并返回。
走向单体地狱(九):MyBatis - 图1

MyBatis 与 Hibernate

Hibernate框架是提供了全面的数据库封装机制的“全自动”ORM,即实现了 POJO 和数据库表之间的映射,以及 SQL 的自动生成和执行。
相对于此,MyBatis 只能算作是“半自动” ORM。其着力点,是在 POJO 类与 SQL 语句之间的映射关系。也就是说,MyBatis 并不会为程序员自动生成 SQL 语句。具体的 SQL 需要程序员自己编写,然后通过 SQL 语句映射文件,将 SQL 所需的参数,以及返回的结果字段映射到指定 POJO。因此,MyBatis 成为了“全自动”ORM 的一种有益补充。

MyBatis 的特点

  • 在 XML 文件中配置 SQL 语句,实现了 SQL 语句与代码的分离,给程序的维护带来了很大便利。
  • 因为需要程序员自己去编写 SQL 语句,程序员可以结合数据库自身的特点灵活控制 SQL 语句,因此能够实现比 Hibernate 等全自动 ORM 框架更高的查询效率,能够完成复杂查询。
  • 简单,易于学习,易于使用,上手快。

走向单体地狱(九):MyBatis - 图2

二. Druid 简介

概述

Druid 是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和 SQL 解析器组成。该项目主要是为了扩展 JDBC 的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计 SQL 信息、SQL 性能收集、SQL 注入检查、SQL 翻译等,程序员可以通过定制来实现自己需要的功能。

各种连接池性能对比测试

测试执行申请归还连接 1,000,000(一百万)次总耗时性能对比。

测试环境

环境 版本
OS OS X 10.8.2
CPU Intel i7 2GHz 4 Core
JVM Java Version 1.7.0_05

基准测试结果

Jdbc Connection Pool 1 thread 2 threads 5 threads 10 threads 20 threads 50 threads
Druid 898 1,191 1,324 1,362 1,325 1,459
tomcat-jdbc 1,269 1,378 2,029 2,103 1,879 2,025
DBCP 2,324 5,055 5,446 5,471 5,524 5 ,415
BoneCP 3 ,738 3,150 3,194 5,681 1 1,018 23,125
jboss-datasource 4,377 2,988 3,680 3,980 32,708 37,742
C3P0 10,841 13,637 10,682 11,055 14,497 20,351
Proxool 16,337 16,187 18,310(Exception) 25,945 33,706(Exception) 39,501 (Exception)

结论

  • Druid 是性能最好的数据库连接池,tomcat-jdbc 和 druid 性能接近。
  • proxool 在激烈并发时会抛异常,完全不靠谱。
  • c3p0 和 proxool 都相当慢,慢到影响 sql 执行效率的地步。
  • bonecp 性能并不优越,采用 LinkedTransferQueue 并没有能够获得性能提升。
  • 除了 bonecp,其他的在 JDK 7 上跑得比 JDK 6 上快
  • jboss-datasource 虽然稳定,但是性能很糟糕

    三. Spring 整合 Druid

    POM

    pom.xml 文件中新增com.alibaba:druidmysql:mysql-connector-java依赖
    1. <dependency>
    2. <groupId>com.alibaba</groupId>
    3. <artifactId>druid</artifactId>
    4. <version>1.1.6</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>mysql</groupId>
    8. <artifactId>mysql-connector-java</artifactId>
    9. <version>5.1.46</version>
    10. </dependency>

    配置数据库连接

    配置数据库连接 jdbc.properties ,配置代码如下:
    1. # JDBC
    2. # MySQL 8.x: com.mysql.cj.jdbc.Driver
    3. jdbc.driverClass=com.mysql.jdbc.Driver
    4. jdbc.connectionURL=jdbc:mysql://192.168.75.134:3306/myshop?useUnicode=true&characterEncoding=utf-8&useSSL=false
    5. jdbc.username=root
    6. jdbc.password=123456
    7. # JDBC Pool
    8. jdbc.pool.init=1
    9. jdbc.pool.minIdle=3
    10. jdbc.pool.maxActive=20
    11. # JDBC Test
    12. jdbc.testSql=SELECT 'x' FROM DUAL

    Spring 集成 Druid

    创建一个名为 spring-context-druid.xmlSpring配置文件,内容如下:
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    5. <!-- 加载配置属性文件 -->
    6. <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>
    7. <!-- 数据源配置, 使用 Druid 数据库连接池 -->
    8. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    9. <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
    10. <property name="driverClassName" value="${jdbc.driverClass}"/>
    11. <!-- 基本属性 url、user、password -->
    12. <property name="url" value="${jdbc.connectionURL}"/>
    13. <property name="username" value="${jdbc.username}"/>
    14. <property name="password" value="${jdbc.password}"/>
    15. <!-- 配置初始化大小、最小、最大 -->
    16. <property name="initialSize" value="${jdbc.pool.init}"/>
    17. <property name="minIdle" value="${jdbc.pool.minIdle}"/>
    18. <property name="maxActive" value="${jdbc.pool.maxActive}"/>
    19. <!-- 配置获取连接等待超时的时间 -->
    20. <property name="maxWait" value="60000"/>
    21. <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    22. <property name="timeBetweenEvictionRunsMillis" value="60000"/>
    23. <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    24. <property name="minEvictableIdleTimeMillis" value="300000"/>
    25. <property name="validationQuery" value="${jdbc.testSql}"/>
    26. <property name="testWhileIdle" value="true"/>
    27. <property name="testOnBorrow" value="false"/>
    28. <property name="testOnReturn" value="false"/>
    29. <!-- 配置监控统计拦截的filters -->
    30. <property name="filters" value="stat"/>
    31. </bean>
    32. </beans>

    配置 Druid 监控中心

    Druid 提供了大量的监控数据,只需要在web.xml中配置一个 Servlet就可以方便的查看这些信息。
    修改 web.xml 配置文件,增加 Druid 提供的 Servlet
    1. <servlet>
    2. <servlet-name>DruidStatView</servlet-name>
    3. <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    4. </servlet>
    5. <servlet-mapping>
    6. <servlet-name>DruidStatView</servlet-name>
    7. <url-pattern>/druid/*</url-pattern>
    8. </servlet-mapping>
    打开浏览器,输入:http://localhost:8080/druid/index.html 浏览器显示效果如下:
    走向单体地狱(九):MyBatis - 图3

四. Spring 整合 MyBatis

POM

pom.xml文件中增加 MyBatis 相关依赖:

  1. <dependency>
  2. <groupId>org.mybatis</groupId>
  3. <artifactId>mybatis</artifactId>
  4. <version>3.2.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mybatis</groupId>
  8. <artifactId>mybatis-spring</artifactId>
  9. <version>1.3.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-jdbc</artifactId>
  14. <version>4.3.17.RELEASE</version>
  15. </dependency>

主要增加了 3 个依赖,分别为 org.mybatis:mybatisorg.mybatis:mybatis-springorg.springframework:spring-jdbc

创建 MyBatis 配置文件

创建一个名为mybatis-config.xml的配置文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <!-- 全局参数 -->
  5. <settings>
  6. <!-- 打印 SQL 语句 -->
  7. <setting name="logImpl" value="STDOUT_LOGGING" />
  8. <!-- 使全局的映射器启用或禁用缓存。 -->
  9. <setting name="cacheEnabled" value="false"/>
  10. <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
  11. <setting name="lazyLoadingEnabled" value="true"/>
  12. <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
  13. <setting name="aggressiveLazyLoading" value="true"/>
  14. <!-- 是否允许单条 SQL 返回多个数据集 (取决于驱动的兼容性) default:true -->
  15. <setting name="multipleResultSetsEnabled" value="true"/>
  16. <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
  17. <setting name="useColumnLabel" value="true"/>
  18. <!-- 允许 JDBC 生成主键。需要驱动器支持。如果设为了 true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false -->
  19. <setting name="useGeneratedKeys" value="false"/>
  20. <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不映射 PARTIAL:部分 FULL:全部 -->
  21. <setting name="autoMappingBehavior" value="PARTIAL"/>
  22. <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) -->
  23. <setting name="defaultExecutorType" value="SIMPLE"/>
  24. <!-- 使用驼峰命名法转换字段。 -->
  25. <setting name="mapUnderscoreToCamelCase" value="true"/>
  26. <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
  27. <setting name="localCacheScope" value="SESSION"/>
  28. <!-- 设置 JDBC 类型为空时,某些驱动程序 要指定值, default:OTHER,插入空值时不需要指定类型 -->
  29. <setting name="jdbcTypeForNull" value="NULL"/>
  30. </settings>
  31. </configuration>

Spring 集成 MyBatis

创建一个名为spring-context-mybatis.xml的 Spring 配置文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  4. <!-- 配置 SqlSession -->
  5. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  6. <!-- 配置数据源 -->
  7. <property name="dataSource" ref="dataSource"/>
  8. <!-- 用于配置对应实体类所在的包,多个 package 之间可以用 ',' 号分割 -->
  9. <property name="typeAliasesPackage" value="com.funtl.my.shop.domain"/>
  10. <!-- 用于配置对象关系映射配置文件所在目录 -->
  11. <property name="mapperLocations" value="classpath:/mapper/**/*.xml"/>
  12. <!-- mybatis配置文件 -->
  13. <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
  14. </bean>
  15. <!-- 扫描 Mapper -->
  16. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  17. <property name="basePackage" value="com.funtl.my.shop.web.admin.dao" />
  18. </bean>
  19. </beans>

五. 第一个 MyBatis 对象关系映射

POM

编写完相关代码后,我们可以使用单元测试查看 MyBatis 的执行效果,需要增加单元测试相关依赖,配置如下:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-test</artifactId>
  4. <version>4.3.17.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>junit</groupId>
  8. <artifactId>junit</artifactId>
  9. <version>4.12</version>
  10. </dependency>

导入 SQL

git地址
https://github.com/JSONCat/demo-java/tree/master/sql

创建通用基类BaseMeta

使用commons-long3下的ReflectionToStringBuilder来生成toString()方法,并实现序列化

  1. public class BaseMeta implements Serializable {
  2. /************
  3. * 转化成string
  4. */
  5. public String toString(){
  6. return ReflectionToStringBuilder.toString(this);
  7. }
  8. }

定义实体类

tb_user表为例,实体类代码如下:

  1. public class TbUser extends BaseMeta {
  2. private Long id;
  3. private String username;
  4. private String password;
  5. private String phone;
  6. private String email;
  7. private Date created;
  8. private Date update;
  9. public Long getId() {
  10. return id;
  11. }
  12. public void setId(Long id) {
  13. this.id = id;
  14. }
  15. public String getUsername() {
  16. return username;
  17. }
  18. public void setUsername(String username) {
  19. this.username = username;
  20. }
  21. public String getPassword() {
  22. return password;
  23. }
  24. public void setPassword(String password) {
  25. this.password = password;
  26. }
  27. public String getPhone() {
  28. return phone;
  29. }
  30. public void setPhone(String phone) {
  31. this.phone = phone;
  32. }
  33. public String getEmail() {
  34. return email;
  35. }
  36. public void setEmail(String email) {
  37. this.email = email;
  38. }
  39. public Date getCreated() {
  40. return created;
  41. }
  42. public void setCreated(Date created) {
  43. this.created = created;
  44. }
  45. public Date getUpdate() {
  46. return update;
  47. }
  48. public void setUpdate(Date update) {
  49. this.update = update;
  50. }
  51. }

定义数据访问接口

注意:Spring 集成 MyBatis 后,不需要手动实现 DAO 层的接口,所有的 SQL 执行语句都写在对应的关系映射配置文件中。

  1. package com.funtl.my.shop.web.admin.dao;
  2. import com.funtl.my.shop.domain.TbUser;
  3. import org.springframework.stereotype.Repository;
  4. import java.util.List;
  5. @Repository
  6. public interface TbUserDao {
  7. /**
  8. * 查询全部用户信息
  9. * @return
  10. */
  11. public List<TbUser> selectAll();
  12. }

定义业务逻辑接口

  1. package com.funtl.my.shop.web.admin.service;
  2. import com.funtl.my.shop.domain.TbUser;
  3. import java.util.List;
  4. public interface TbUserService {
  5. /**
  6. * 查询全部用户信息
  7. * @return
  8. */
  9. public List<TbUser> selectAll();
  10. }

实现业务逻辑接口

  1. package com.funtl.my.shop.web.admin.service.impl;
  2. import com.funtl.my.shop.domain.TbUser;
  3. import com.funtl.my.shop.web.admin.dao.TbUserDao;
  4. import com.funtl.my.shop.web.admin.service.TbUserService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. @Service
  9. public class TbUserServiceImpl implements TbUserService {
  10. @Autowired
  11. private TbUserDao tbUserDao;
  12. @Override
  13. public List<TbUser> selectAll() {
  14. return tbUserDao.selectAll();
  15. }
  16. }

定义映射文件

映射文件,简称为 Mapper,主要完成 DAO 层中 SQL 语句的映射。映射文件名随意,一般放在 src/resources/mapper 文件夹中。这里映射文件名称定为 TbUserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.funtl.my.shop.web.admin.dao.TbUserDao">
  4. <select id="selectAll" resultType="TbUser">
  5. SELECT
  6. a.id,
  7. a.username,
  8. a.password,
  9. a.phone,
  10. a.email,
  11. a.created,
  12. a.updated
  13. FROM
  14. tb_user AS a
  15. </select>
  16. </mapper>

创建单元测试

所有工作准备就绪,我们就可以测试 MyBatis 是否能够正常执行了。创建一个单元测试类,代码如下:

  1. package com.funtl.my.shop.web.admin.service.test;
  2. import com.funtl.my.shop.domain.TbUser;
  3. import com.funtl.my.shop.web.admin.dao.TbUserDao;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import java.util.List;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration({"classpath:spring-context.xml", "classpath:spring-context-druid.xml", "classpath:spring-context-mybatis.xml"})
  12. public class TbUserServiceTest {
  13. @Autowired
  14. private TbUserDao tbUserDao;
  15. @Test
  16. public void testSelectAll() {
  17. List<TbUser> tbUsers = tbUserDao.selectAll();
  18. for (TbUser tbUser : tbUsers) {
  19. System.out.println(tbUser.getUsername());
  20. }
  21. }
  22. }

六. MyBatis 单表 CRUD 操作

INSERT

继续以 tb_user 表为例,修改映射文件,增加如下配置:

  1. <insert id="insert">
  2. INSERT INTO tb_user (
  3. id,
  4. username,
  5. password,
  6. phone,
  7. email,
  8. created,
  9. updated
  10. )
  11. VALUES
  12. (
  13. #{id},
  14. #{username},
  15. #{password},
  16. #{phone},
  17. #{email},
  18. #{created},
  19. #{update}
  20. )
  21. </insert>

单元测试代码如下:

  1. @Test
  2. public void testInsert() {
  3. TbUser tbUser = new TbUser();
  4. tbUser.setEmail("admin@admin.com");
  5. tbUser.setPassword("admin");
  6. tbUser.setPhone("15888888888");
  7. tbUser.setUsername("Lusifer");
  8. tbUser.setCreated(new Date());
  9. tbUser.setUpdate(new Date());
  10. tbUserDao.insert(tbUser);
  11. }

DELETE

继续以tb_user表为例,修改映射文件,增加如下配置:

  1. <delete id="delete">
  2. DELETE FROM tb_user WHERE id = #{id}
  3. </delete>

单元测试代码如下:

  1. @Test
  2. public void testDelete() {
  3. TbUser tbUser = new TbUser();
  4. tbUser.setId(37L);
  5. tbUserDao.delete(tbUser);
  6. }

查询单个对象

继续以 tb_user 表为例,修改映射文件,增加如下配置:

  1. <select id="getById" resultType="TbUser">
  2. SELECT
  3. a.id,
  4. a.username,
  5. a.password,
  6. a.phone,
  7. a.email,
  8. a.created,
  9. a.updated AS "update"
  10. FROM
  11. tb_user AS a
  12. WHERE
  13. a.id = #{id}
  14. </select>

单元测试代码如下:

  1. @Test
  2. public void testGetById() {
  3. TbUser tbUser = tbUserDao.getById(36L);
  4. System.out.println(tbUser.getUsername());
  5. }

UPDATE

继续以 tb_user 表为例,修改映射文件,增加如下配置:

  1. <update id="update">
  2. UPDATE
  3. tb_user
  4. SET
  5. username = #{username},
  6. password = #{password},
  7. phone = #{phone},
  8. email = #{email},
  9. created = #{created},
  10. updated = #{update}
  11. WHERE id = #{id}
  12. </update>

单元测试代码如下:

  1. @Test
  2. public void testUpdate() {
  3. TbUser tbUser = tbUserDao.getById(36L);
  4. tbUser.setUsername("Lusifer");
  5. tbUserDao.update(tbUser);
  6. }

使用模糊查询

继续以tb_user 表为例,修改映射文件,增加如下配置:

  1. <select id="selectByName" resultType="TbUser">
  2. SELECT
  3. a.id,
  4. a.username,
  5. a.password,
  6. a.phone,
  7. a.email,
  8. a.created,
  9. a.updated AS "update"
  10. FROM
  11. tb_user AS a
  12. WHERE
  13. a.username LIKE CONCAT ('%', #{username}, '%')
  14. </select>

在进行模糊查询时,需要进行字符串的拼接。SQL 中的字符串的拼接使用的是函数concat(arg1, arg2, …)。注意不能使用 Java 中的字符串连接符 +。
单元测试代码如下:

  1. @Test
  2. public void testSelectByName() {
  3. List<TbUser> tbUsers = tbUserDao.selectByName("uni");
  4. for (TbUser tbUser : tbUsers) {
  5. System.out.println(tbUser.getUsername());
  6. }
  7. }

七. MyBatis 动态 SQL

动态 SQL,主要用于解决查询条件不确定的情况:在程序运行期间,根据用户提交的查询条件进行查询。提交的查询条件不同,执行的 SQL 语句不同。若将每种可能的情况均逐一列出,对所有条件进行排列组合,将会出现大量的 SQL 语句。此时,可使用动态 SQL 来解决这样的问题。
走向单体地狱(九):MyBatis - 图4
动态 SQL,即通过 MyBatis 提供的各种标签对条件作出判断以实现动态拼接 SQL 语句。
这里的条件判断使用的表达式为 OGNL 表达式。常用的动态 SQL 标签有 <if><where><choose><foreach>等。

注意事项

在 mapper 的动态 SQL 中若出现大于号(>)、小于号(<)、大于等于号(>=),小于等于号(<=)等符号,最好将其转换为实体符号。否则,XML 可能会出现解析出错问题。
特别是对于小于号(<),在 XML 中是绝对不能出现的。否则,一定出错。

if 标签

对于该标签的执行,当 test 的值为 true 时,会将其包含的 SQL 片断拼接到其所在的 SQL 语句中。
本例实现的功能是:查询出满足用户提交查询条件的所有学生。用户提交的查询条件可以包含一个姓名的模糊查询,同时还可以包含一个年龄的下限。当然,用户在提交表单时可能两个条件均做出了设定,也可能两个条件均不做设定,也可以只做其中一项设定。
这引发的问题是,查询条件不确定,查询条件依赖于用户提交的内容。此时,就可使用动态 SQL 语句,根据用户提交内容对将要执行的 SQL 进行拼接。

定义映射文件

为了解决两个条件均未做设定的情况,在 where 后添加了一个“1=1”的条件。这样就不至于两个条件均未设定而出现只剩下一个 where,而没有任何可拼接的条件的不完整 SQL 语句。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.lusifer.mybatis.dao.DynamicStudentDao">
  4. <!-- if -->
  5. <select id="selectByIf" resultType="com.lusifer.mybatis.entity.Student">
  6. SELECT
  7. id,
  8. name,
  9. age,
  10. score
  11. FROM
  12. student
  13. WHERE 1 = 1
  14. <if test="name != null and name != ''">
  15. AND name LIKE concat('%', #{name}, '%')
  16. </if>
  17. <if test="age != null and age > 0">
  18. AND age > #{age}
  19. </if>
  20. </select>
  21. </mapper>

where 标签

<if/> 标签的中存在一个比较麻烦的地方:需要在 where后手工添加1=1的子句。因为,若where后的所有 <if/>条件均为false,而 where 后若又没有1=1子句,则 SQL 中就会只剩下一个空的where,SQL 出错。所以,在 where 后,需要添加永为真子句1=1,以防止这种情况的发生。但当数据量很大时,会严重影响查询效率。

定义映射文件

SELECT id, name, age, score FROM student AND name LIKE concat(‘%’, #{name}, ‘%’) AND age > #{age} ## choose 标签 该标签中只可以包含 `,可以包含多个 `与一个 ``。它们联合使用,完成 Java 中的开关语句 switch..case 功能。
本例要完成的需求是,若姓名不空,则按照姓名查询;若姓名为空,则按照年龄查询;若没有查询条件,则没有查询结果。

定义映射文件

  1. <!-- choose -->
  2. <select id="selectByChoose" resultType="com.lusifer.mybatis.entity.Student">
  3. SELECT
  4. id,
  5. name,
  6. age,
  7. score
  8. FROM
  9. student
  10. <where>
  11. <choose>
  12. <when test="name != null and name != ''">
  13. AND name LIKE concat('%', #{name}, '%')
  14. </when>
  15. <when test="age != null and age > 0">
  16. AND age > #{age}
  17. </when>
  18. <otherwise>
  19. AND 1 != 1
  20. </otherwise>
  21. </choose>
  22. </where>
  23. </select>

foreach 标签-遍历数组

<foreach/>标签用于实现对于数组与集合的遍历。对其使用,需要注意:

  • collection 表示要遍历的集合类型,这里是数组,即 array。
  • opencloseseparator 为对遍历内容的 SQL 拼接。

本例实现的需求是,查询出 id 为 2 与 4 的学生信息。

定义映射文件

动态 SQL 的判断中使用的都是 OGNL 表达式。OGNL 表达式中的数组使用 array表示,数组长度使用 array.length 表示。
走向单体地狱(九):MyBatis - 图5

  1. <!-- foreach -->
  2. <select id="selectByForeach" resultType="com.lusifer.mybatis.entity.Student">
  3. <!-- select * from student where id in (2, 4) -->
  4. SELECT
  5. id,
  6. name,
  7. age,
  8. score
  9. FROM
  10. student
  11. <if test="array != null and array.length > 0">
  12. WHERE id IN
  13. <foreach collection="array" open="(" close=")" item="id" separator=",">
  14. #{id}
  15. </foreach>
  16. </if>
  17. </select>

foreach 标签-遍历集合

遍历集合的方式与遍历数组的方式相同,只不过是将 array 替换成了 list

遍历泛型为基本类型的 List

定义 DAO 接口

  1. /**
  2. * 使用 foreach 标签以 list 基本类型的形式查询
  3. * @param ids
  4. * @return
  5. */
  6. public List<Student> selectByForeachWithListBase(List<Long> ids);

定义映射文件

  1. <!-- foreach -->
  2. <select id="selectByForeachWithListBase" resultType="com.lusifer.mybatis.entity.Student">
  3. <!-- select * from student where id in (2, 4) -->
  4. SELECT
  5. id,
  6. name,
  7. age,
  8. score
  9. FROM
  10. student
  11. <if test="list != null and list.size > 0">
  12. WHERE id IN
  13. <foreach collection="list" open="(" close=")" item="id" separator=",">
  14. #{id}
  15. </foreach>
  16. </if>
  17. </select>

遍历泛型为自定义类型的 List

定义 DAO 接口

  1. /**
  2. * 使用 foreach 标签以 list 自定义类型的形式查询
  3. * @param students
  4. * @return
  5. */
  6. public List<Student> selectByForeachWithListCustom(List<Student> students);

定义映射文件

  1. <!-- foreach -->
  2. <select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student">
  3. <!-- select * from student where id in (2, 4) -->
  4. SELECT
  5. id,
  6. name,
  7. age,
  8. score
  9. FROM
  10. student
  11. <if test="list != null and list.size > 0">
  12. WHERE id IN
  13. <foreach collection="list" open="(" close=")" item="student" separator=",">
  14. #{student.id}
  15. </foreach>
  16. </if>
  17. </select>

sql 标签

<sql/>标签用于定义 SQL 片断,以便其它 SQL 标签复用。而其它标签使用该 SQL 片断, 需要使用 <include/>子标签。该 <sql/>标签可以定义 SQL 语句中的任何部分,所以<include/>子标签可以放在动态 SQL 的任何位置。

修改映射文件

  1. <sql id="select">
  2. SELECT
  3. id,
  4. name,
  5. age,
  6. score
  7. FROM
  8. student
  9. </sql>
  10. <!-- foreach -->
  11. <select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student">
  12. <!-- select * from student where id in (2, 4) -->
  13. <include refid="select" />
  14. <if test="list != null and list.size > 0">
  15. WHERE id IN
  16. <foreach collection="list" open="(" close=")" item="student" separator=",">
  17. #{student.id}
  18. </foreach>
  19. </if>
  20. </select>