MyBatis3学习笔记

目录

一、MyBatis简介

1.什么是Mybatis

2.MyBatis优点

3.MyBatis历史

二、MyBatis初运行

1.安装MyBatis

2.使用MyBatis示例

3.接口式编程

总结

三、全局配置文件

1.properties属性

2.settings设置

3.typeAliases别名处理器

4.typeHandlers类型处理器

5.plugins插件

6.environments环境

7.databaseIdProvider

8.mapper映射

四、SQL映射文件

1.insert、update、delete元素

2.主键生成方式

3.参数传递

1.单个参数

2.多个参数

3.命名参数

运行成功   4.POJO&Map&To:

4.参数处理

5.select元素

6.自动映射

7.自定义规则resultMap

8.resultMap关联查询

单个对象级联属性封装

 association定义关联单个对象封装规则

 association分步查询

多对象结果级联查询 

多对象结果collection分布查询&延迟查询

discriminator鉴别器

五、动态SQL

1.if

2.trim

3.choose

4.set

5.for each

6.内置参数

7.bind绑定

8.抽取可重用sql片段

六、缓存机制

一级缓存

二级缓存

缓存原理图示

第三方缓存整合

七、MyBatis-Spring整合

八、MyBatis-逆向工程

MyBatis Generator

MBG使用

九、MyBatis工作原理

 1、获取sqlSessionFactory对象:

2、获取sqlSession对象

  3、获取接口的代理对象(MapperProxy)

4、执行增删改查方法

总结:

十、插件开发

插件原理

插件编写


本次课程的主要内容:MyBatis配置文件编写,MyBatis动态SQL,MyBatis缓存机制,MyBatis-Spring整合,MyBatis逆向工程,MyBatis高级内容(源码解析,单/多插件运行机制,四大对象工作原理,自定义TypeHandler、MyBatis存储过程&游标处理等)。

 IDE:IDEA
数据库:mysql 5.7
核心技术:mybatis-3.5.7

一、MyBatis简介

1. MyBatis历史

• 原是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation 迁移到了Google Code,随着开发团队转投Google Code旗下, iBatis3.x正式更名为MyBatis ,代码于2013年11月迁移到Github(下载地址见后)。

• iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。 iBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO)

2. 什么是Mybatis

• MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架

• MyBatis避免了几乎所有的JDBC代码和手动设参数以及获取结果集的操作。

• MyBatis可以使用简单的XML或注解用于配置和原始映射将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录

3. MyBatis优点

JDBC的问题

前阶段我们已经学习过的和数据库交互的技术有JDBC中的QueryRunner和Spring中的jdbcTemplate,执行过程大致如下。

  • SQL夹在Java代码块里,耦合度高导致硬编码内伤
  • 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见

Hibernate的问题

我们进一步采取框架的构想,如Hibernate。其把javabean自动映射成数据库中的一条记录。开发人员只需关心javabean映射成哪个数据记录,不关心实现的过程。

  • 长难复杂SQL,对于Hibernate而言处理也不容易
  • 内部自动生产的SQL,不容易做特殊优化。对发开人员而言,核心SQL还是需要自己优化。
  • 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难导致数据库性能下降。

mybatis优势

Mybatis开放了部分操作给开发者。将编写sql的部分提取出来写成一个配置文件,剩下的过程由mybatis封装完成。实现了SQL和java编码解耦,只需要掌握SQL语句。

  • mybatis是半自动、轻量级的持久层框架。 
  • sql和java编码分开,功能边界清晰,一个专注业务、一个专注数据。

二、MyBatis初运行

1.安装MyBatis

不使用maven情况

要使用MyBatis,只需将mybatis-x.x.x.jar文件置于类路径(classpath)中即可。

访问地址https://github.com/mybatis/mybatis-3/,选择所需要的版本下载相应的jar包和源码包

mybatis的官方文档地址https://mybatis.org/mybatis-3/zh/index.html

解压后:

在IDEA中创建Java工程和相关目录,引入所需jar包,注意将conf文件夹转为配置文件夹(右键--mark Directory as --resources root)

使用maven情况

若使用maven构建项目的话可跳过上述下载导包操作,需将下面的依赖代码置于 pom.xml 文件中:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

2.使用MyBatis示例

1. 数据库中创建一张测试表

CREATE TABLE tbl_employee(
	id INT(11) PRIMARY KEY AUTO_INCREMENT,
	last_name VARCHAR(255),
	gender CHAR(1),
	email VARCHAR(255)
)

2.创建对应的javaBean

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private String gender;
    ... ...
}

3. 导入相关jar包

 其中log4j日志包要能运行,需要在配置文件夹中使用log4j.xml(官网下载直接用),代码如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

4. 创建mybatis配置文件

MyBatis的全局配置文件包含了影响MyBatis行为甚深的设置和属性信息、如数据库连接池信息以及决定事务作用域和控制方式的事务管理器等,后面会再探讨 XML 配置文件的详细内容。我们先参照官方文件的配置示例

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="12345"/>
            </dataSource>
        </environment>
    </environments>
    <!--将我们写好的sql映射文件(EmployeeMapper.xml)注册到全局配置文件中(mybatis-config.xml)-->
    <mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>
</configuration>

注意 XML 头部的声明,它用来验证 XML 文档的正确性。environment 元素体中包含了事务管理和连接池的配置。mappers 元素则包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。

5.根据配置文件创建SqlSessionFactory,从 SqlSessionFactory 中获取 SqlSession,使用sqlsession执行增删改查

MyBatis的应用都是以一个SqlSessionFactory的实例为核心的。SqlSessionFactory 的实例可以通过SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。

public class MybatisText {
    /**
     * 1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
     * 2.
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        //1.根据全局配置文件,利用SqlSessionFactoryBuilder创建SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.使用SqlSessionFactory获取sqlSession对象,能直接执行已映射的sql语句。一个SqlSession对象代表和数据库的一次会话。
        SqlSession openSession = sqlSessionFactory.openSession();
                //3.使用SqlSession根据方法id进行操作
                try {
                    //1.sql的唯一标识,通常namespace+id的方式
                    //2.执行sql要用的参数
                    Employee employee = openSession.selectOne("com.atguigu.mybatis.EmployeeMapper.selectEmp",1);
                    System.out.println(employee);
                } finally {
                    openSession.close();
                }
    }

6. 创建SQL映射文件
映射文件的作用就相当于是定义Dao接口的实现类如何工作。这也是我们使用MyBatis时编写的最多的文件。

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">
<!--
namespace名称空间
id:唯一标识 namespace+id
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
-->
<mapper namespace="com.atguigu.mybatis.EmployeeMapper"><!--名字任取(后面常采用接口式编程)-->
    <select id="selectEmp" resultType="com.atguigu.mybatis.bean.Employee"><!--查出记录的类型-->
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
 </select>
</mapper>

7.测试

步骤总结:
1.创建全局配置文件
2.根据全局配置文件创建SqlSessionFactory对象
3.创建sql映射文件(配置了每一个sql,以及sql的封装规则等) 
4.将sql映射文件注册在全局配置文件中

细节:
1.根据配置文件创建SqlSessionFactory,从 SqlSessionFactory 中获取 SqlSession,使用sqlsession执行增删改查。一个sqlSession就是代表和数据库的一次会话,用完关闭
2.使用sql的唯一标志来告诉MyBatis执行哪个sql(后面我们采用接口编程的方法取代)。sql都是保存在sql映射文件中的。

3.接口式编程

SqlSession可以直接调用方法的唯一标注(namespace+id)进行数据库操作,但是我们一般还是推荐使用SqlSession获取到Dao接口的代理类,执行代理对象的方法,可以更安全的进行类型检查操作

1.创建一个Dao接口

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

2.修改Mapper文件

	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}
	
    @Test
	public void test01() throws IOException {
		// 1、获取sqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		// 2、获取sqlSession对象
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			// 3、获取接口的实现类对象
			//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			Employee employee = mapper.getEmpById(1);
			System.out.println(mapper.getClass());
			System.out.println(employee);
		} finally {
			openSession.close();
		}
	}

employeeMapper.xml

采用接口编程方法的好处:

拥有更强的类型检查,有明确的返回值,将dao层的规范和实现分离出来,方便开发扩展。

总结

1、接口式编程
    未使用mybatis之前,一个dao接口对应一个实现类;使用mybatis后,dao接口以XXXMapper命名,有一个与之对应的sql映射文件    
    原生:         Dao        ====>  DaoImpl
    mybatis:    Mapper    ====>  xxMapper.xml
2、SqlSession代表和数据库的一次会话,用完必须关闭;
3、SqlSession和connection一样都是非线程安全。每次使用都应该去获取新的对象。
4、mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。(将接口和xml进行绑定)
        EmployeeMapper empMapper =    sqlSession.getMapper(EmployeeMapper.class);
5、两个重要的配置文件:
        mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息
        sql映射文件:保存了每一个sql语句的映射信息:将sql抽取出来。    

三、全局配置文件

MyBatis的配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(properties)信息。文档的顶层结构如下:

1.properties属性

1、mybatis可以使用properties来引入外部properties配置文件的内容;
            resource:引入类路径下的资源
            url:引入网络路径或者磁盘路径下的资源

示例:类路径下有dbconfig.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

mybatis-config.xml(此部分后续会和spring整合,此形式不常用了)

<properties resource="dbconfig.properties"></properties>
<environments default="dev_mysql">
    <environment id="dev_mysql">
        <transactionManager type="JDBC"></transactionManager>
		<dataSource type="POOLED">
			<property name="driver" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
        </dataSource>
    </environment>
</environments>

 • 如果属性在不只一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:
      在 properties 元素体内指定的属性首先被读取。
      然后根据 properties 元素中的 resource 属性读取类路径下属性文件或根据 url 属性指定的路径读取属性文件,并覆盖已读取的同名属性。
      最后读取作为方法参数传递的属性,并覆盖已读取的同名属性。

2.settings设置

这是MyBatis中极为重要的调整设置,它们会改变MyBatis的运行时行为。(边用边学)

settings包含很多重要的设置项
    setting:用来设置每一个设置项
        name:设置项名
        value:设置项取值

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/><!--开启自动驼峰规则为例-->
</settings>

3.typeAliases别名处理器

别名处理器可以为我们的java类型起别名,别名不区分大小写。类型别名可以方便我们引用某个类。(一般为了好找写好的类,我们还是会使用全类名的方式)

1、typeAlias:为某个java类型起别名
         type:指定要起别名的类型的类名,默认别名就是类名小写
         alias:指定新的别名

<typeAliases><!--m默认类名employee-->
	<typeAlias type="com.atguigu.mybatis.bean.Employee" alias="emp"/>
</typeAliases>

类很多的情况下,可以批量设置别名。这个包下的每一个类创建一个默认的别名,就是简单类名小写。

2.package:为某个包下的所有类批量起别名 
    name:指定包名(为当前包以及下面所有的后代包的每一个类都起一个默认别名(类名小写))

<typeAliases>
    <!--给bean包下的类起别名,默认的别名都是类的小写-->
	<package name="com.atguigu.mybatis.bean"/>
</typeAliases>

3.为避免批量起别命名带来冲突(包和子包有同名类),使用@Alias注解为某个类型指定新的别名

@Alias("emp")
public class Employee {
    private Integer id;
    private String lastName;
    ......
}

值得注意的是,MyBatis已经为许多常见的 Java 类型内建了相应的类型别名。它们都是大小写不敏感的,我们在起别名的时候千万不要占用已有的别名。

4.typeHandlers类型处理器

无论是MyBatis在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。

作用:架起java类型和数据库类型一一映射的桥梁

日期类型的处理
日期和时间的处理,JDK1.8以前一直是个头疼的问题。我们通常使用JSR310规范领导者Stephen Colebourne创建的Joda-Time来操作。1.8已经实现全部的JSR310规范了。
    • 日期时间处理上,我们可以使用MyBatis基于JSR310(Date and Time API)编写的各种日时间类型处理器。
    • MyBatis3.4以前的版本需要我们手动注册这些处理器,以后的版本都是自动注册

自定义类型处理器
我们可以重写类型处理器或创建自己的类型处理器来处理不支持的或非标准的类型。(放到后部分学习)
步骤:
    • 1 实现org.apache.ibatis.type.TypeHandler接口或者继承org.apache.ibatis.type.BaseTypeHandler
    • 2 指定其映射某个JDBC类型(可选操作)
    • 3 在mybatis全局配置文件中注册

5.plugins插件

等后续讲完mybatis运行原理后细讲,先做简单介绍

插件是MyBatis提供的一个非常强大的机制,我们可以通过插件来修改MyBatis的一些核心行为插件通过动态代理机制,可以介入四大对象的任何一个方法的执行。后面会有专门的章节我们来介绍mybatis运行原理以及插件
    • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
    • ParameterHandler (getParameterObject, setParameters) 
    • ResultSetHandler (handleResultSets, handleOutputParameters) 
    • StatementHandler (prepare, parameterize, batch, update, query) 

6.environments环境

MyBatis可以配置多种环境,比如开发、测试和生 产环境需要有不同的配置
• 每种环境使用一个environment标签进行配置并指 定唯一标识符
可以通过environments标签中的default属性指定 一个环境的标识符来快速的切换环境

environment-指定具体环境

• id:指定当前环境的唯一标识

• transactionManager、和dataSource子标签都必须有

transactionManager标签:事务管理器;(我们通常交给spring完成事务管理,了解即可)

type: JDBC | MANAGED | 自定义
        – JDBC:使用了 JDBC 的提交和回滚设置,依赖于从数据源得到的连接来管理事务范围。
        JdbcTransactionFactory的别名
        – MANAGED:不提交或回滚一个连接、让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 ManagedTransactionFactory
        – 自定义:实现TransactionFactory接口,type=全类名/别名

dataSource标签
• type: UNPOOLED | POOLED | JNDI | 自定义
  – UNPOOLED:不使用连接池,UnpooledDataSourceFactory
  – POOLED:使用连接池, PooledDataSourceFactory
  – JNDI: 在EJB 或应用服务器这类容器中查找指定的数据源
  – 自定义:实现DataSourceFactory接口,定义数据源的获取方式。
实际开发中我们使用Spring管理数据源,并进行事务控制的配置来覆盖上述配置别名

<environments default="dev_mysql">
		<environment id="dev_mysql">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	
		<environment id="dev_oracle">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${orcl.driver}" />
				<property name="url" value="${orcl.url}" />
				<property name="username" value="${orcl.username}" />
				<property name="password" value="${orcl.password}" />
			</dataSource>
		</environment>
	</environments>

7.databaseIdProvider

MyBatis支持多数据库厂商,使用databaseIdProvider标签可以根据不同的数据库厂商执行不同的语句

	<databaseIdProvider type="DB_VENDOR">
		<!-- 为不同的数据库厂商起别名 -->
		<property name="MySQL" value="mysql"/>
		<property name="Oracle" value="oracle"/>
		<property name="SQL Server" value="sqlserver"/>
	</databaseIdProvider>

Type: DB_VENDOR
        – 使用MyBatis提供的VendorDatabaseIdProvider解析数据库厂商标识。也可以实现DatabaseIdProvider接口来自定义。
• Property-name:数据库厂商标识
• Property-value:为标识起一个别名,方便SQL语句使用databaseId属性引用

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
    <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee" >
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
 </select>
    <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee" databaseId="mysql">
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
 </select>
    <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee" databaseId="oracle">
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
 </select>
</mapper>

MyBatis匹配规则如下:
  – 1、如果没有配置databaseIdProvider标签,那么databaseId=null
  – 2、如果配置了databaseIdProvider标签,使用标签配置的name去匹配数据库信息,匹配上设置databaseId=配置指定的值,否则依旧为null
  – 3、如果databaseId不为null,他只会找到配置databaseId的sql语句
  – 4、MyBatis 会加载不带 databaseId 属性和带有匹配当前数据库  databaseId 属性的所有语句。如果同时找到带有 databaseId 和不带databaseId 的相同语句,则不带标识的会被舍弃。

8.mapper映射

将sql映射注册到全局配置中

	<!-- mappers:将sql映射注册到全局配置中 -->
	<mappers>
		<!-- 
			mapper:注册一个sql映射 
				注册配置文件
				resource:引用类路径下的sql映射文件
					mybatis/mapper/EmployeeMapper.xml
				url:引用网路路径或者磁盘路径下的sql映射文件
					file:///var/mappers/AuthorMapper.xml
					
				注册接口
				class:引用(注册)接口,
					1、有sql映射文件,映射文件名必须和接口同名,并且放在与接口同一目录下;
					2、没有sql映射文件,所有的sql都是利用注解写在接口上;
					推荐:
						比较重要的,复杂的Dao接口我们来写sql映射文件
						不重要,简单的Dao接口为了开发快速可以使用注解;
		-->
		<!-- <mapper resource="mybatis/mapper/EmployeeMapper.xml"/> -->
        <!-- <mapper class="com.atguigu.mybatis.dao.EmployeeMapper"/> EmployeeMapper.java和EmployeeMapper.xml要在一个文件夹内-->
		<!-- <mapper class="com.atguigu.mybatis.dao.EmployeeMapperAnnotation"/> -->
		
		<!-- 批量注册: -->
		<package name="com.atguigu.mybatis.dao"/>
	</mappers>
public interface EmployeeMapperAnnotation {
	
	@Select("select * from tbl_employee where id=#{id}")
	public Employee getEmpById(Integer id);
}

四、SQL映射文件

映射文件指导着MyBatis如何进行数据库增删改查,有着非常重要的意义;

1.insert、update、delete元素

接口:

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    
    public void addEmp(Employee employee);
    
    public void deleteEmp(Integer id);
    
    public void updateEmp(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">
<!--
namespace名称空间,指定为接口的全类名
id:唯一标识, 可以被用来引用这条语句
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
-->
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
    <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee" databaseId="mysql">
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>

<!--    public void addEmp(Employee employee);-->
<!--    parameterType:将会传入这条语句的参数的类全限定名或别名。这个属性是可选的可以省略-->
    <insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee">
        insert into tbl_employee(last_name,email,gener) value (#{lastName},#{email},#{gender})
    </insert>

<!--public void deleteEmp(Integer id);-->
    <delete id="deleteEmp">
        delete from tbl_employee where id=#{id}
    </delete>
<!--  public void updateEmp(Employee employee);-->
    <update id="updateEmp">
        update tbl_employee set last_name = #{lastName},email=#{email},gender=#{gender}
    </update>
</mapper>

功能测试:

 @Test
    public void test2() throws IOException {
        //根据全局配置文件,利用SqlSessionFactoryBuilder创建SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //1.获取到的sqlSession不会自动提交数据
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            //测试添加
            //Employee employee = new Employee(null, "jerry", "jerry@email", "0");
            //mapper.addEmp(employee);
            //测试更新
            //Employee employee = new Employee(2, "jerry", "jerry@email", "0");
            //mapper.updateEmp(employee);
            //测试删除
            mapper.deleteEmp(2);
            //2.手动提交数据
            openSession.commit();
        }finally {
            openSession.close();
        }
    }

1.mybatis允许增删改直接定义以下类型返回值 Integer、Long、Boolean、void。(运行sql语句后返回的值)

public Integer addEmp(Employee employee);

 Integer integer = mapper.addEmp(employee);

2.我们需要手动提交数据

sqlSessionFactory.openSession();手动提交
sqlSessionFactory.openSession(true);自动提交

2.主键生成方式

• 获取自增主键的值:
mysql支持自增主键。自增主键值的获取,mybatis和原生JDBC一样也是利用statement.getGenreatedKeys()获取;
        useGeneratedKeys="true" 使用自增主键获取主键值策略
        keyProperty 指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性

<insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee"
		useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
		insert into tbl_employee(last_name,email,gender) 
		values(#{lastName},#{email},#{gender})
</insert>
 Employee employee = new Employee(null, "je", "jerry@email", "0");
 mapper.addEmp(employee);
 System.out.println(employee.getId());//能获取到非空的主键值

 • 获取非自增主键的值:
        Oracle不支持自增主键,Oracle使用序列来模拟自增;
        每次插入的数据的主键是从序列中拿到的值,如何获取到这个值;

<insert id="addEmp" databaseId="oracle">
		<!-- 
		keyProperty:查出的主键值封装给javaBean的哪个属性
		order="BEFORE":当前sql在插入sql之前运行
			   AFTER:当前sql在插入sql之后运行
		resultType:查出的数据的返回值类型
		
		BEFORE运行顺序:
			先运行selectKey查询id的sql;查出id值封装给javaBean的id属性
			在运行插入的sql;就可以取出id属性对应的值
		AFTER运行顺序:
			先运行插入的sql(从序列中取出新值作为id);
			再运行selectKey查询id的sql;
		 -->
		<selectKey keyProperty="id" order="BEFORE" resultType="Integer">
			<!-- 编写查询主键的sql语句 -->
			<!-- BEFORE-->
			select EMPLOYEES_SEQ.nextval from dual 
			<!-- AFTER:查询序列中的当前值
			 select EMPLOYEES_SEQ.currval from dual -->
		</selectKey>
		
		<!-- 插入时的主键是从序列中拿到的 -->
		<!-- BEFORE:-->
		insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) 
		values(#{id},#{lastName},#{email<!-- ,jdbcType=NULL -->}) 
		<!-- AFTER:
		insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) 
		values(employees_seq.nextval,#{lastName},#{email}) -->
	</insert>

3.参数传递

1.单个参数

mybatis不会做特殊处理,
            #{参数名/任意名}:取出参数值。

  <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee" databaseId="mysql">
    <!--此处写#{任意值}不会影响取值结果-->
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}    

  </select>

2.多个参数

mybatis会做特殊处理。

示例:

<!--  public Employee getEmpByIdAndLastName(Integer id,String lastName);-->
 	<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 	</select>

测试 

try{
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
    System.out.println(employee);
}

运行结果:

异常报错:
    org.apache.ibatis.binding.BindingException: 
    Parameter 'id' not found. 
    Available parameters are [1, 0, param1, param2]
    操作:
        方法:public Employee getEmpByIdAndLastName(Integer id,String lastName);
        取值:#{id},#{lastName}

原因分析:
       多个参数会被封装成一个map,key:param1...paramN,或者参数的索引也可以
                                                         value:传入的参数值

修正:

<!--  public Employee getEmpByIdAndLastName(Integer id,String lastName);-->
 	<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{param1} and last_name=#{param2}
 	</select>

上述修正方法可以正常使用,但参数命名比较模糊,改进:

3.命名参数

【命名参数】:明确指定封装参数时map的key;@Param("id")
            多个参数会被封装成 一个map,
                key:使用@Param注解指定的值
                value:参数值 
               #{指定的key}取出对应的参数值

改进后写法:

<!--  public Employee getEmpByIdAndLastName(@Param("id")Integer id,@Param("lastName")String lastName);-->
 	<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 	</select>

 测试:

try{
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
    System.out.println(employee);
}

运行成功   

4.POJO&Map&To:

如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo;
            #{属性名}:取出传入的pojo的属性值    

如果多个参数不是业务模型中的数据,没有对应的pojo,不会经常使用到,为了方便,我们也可以传入map
            #{key}:取出map中对应的值

 	<!-- public Employee getEmpByMap(Map<String, Object> map); -->
 	<select id="getEmpByMap" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tal_empolyee where id=${id} and last_name=#{lastName}
 	</select>
try{
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Map<String, Object> map = new HashMap<>();
    map.put("id", 2);
    map.put("lastName", "Tom");
    Employee employee = mapper.getEmpByMap(map);
    System.out.println(employee);
}

如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象
Page{
    int index;
    int size;
}

思考:  
public Employee getEmp(@Param("id")Integer id,String lastName);
    取值:id==>#{id/param1}   lastName==>#{param2}

public Employee getEmp(Integer id,@Param("e")Employee emp);
    取值:id==>#{param1}    lastName===>#{param2.lastName/e.lastName}

##特别注意:如果是Collection(List、Set)类型或者是数组,也会特殊处理。也是把传入的list或者数组封装在map中。
            key:Collection(collection),如果是List还可以使用这个key(list),数组(array)
public Employee getEmpById(List<Integer> ids);
    取值:取出第一个id的值:   #{list[0]}
    
结合源码,mybatis怎么处理参数(了解内容)

总结:参数多时会封装map,为了不混乱,我们可以使用@Param来指定封装时使用的key;
#{key}就可以取出map中的值;

EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpByIdAndLastName(1, "tom");

mapper是代理对象。

paramNameResolver是解析参数封装map的源码

public Object getNamedParams(Object[] args) {
        int paramCount = this.names.size();
        if (args != null && paramCount != 0) {
            if (!this.hasParamAnnotation && paramCount == 1) {//只有一个元素并且没有注解
                Object value = args[(Integer)this.names.firstKey()];
                return wrapToMapIfCollection(value, this.useActualParamName ? (String)this.names.get(0) : null);
            } else {
                Map<String, Object> param = new ParamMap();
                int i = 0;

                for(Iterator var5 = this.names.entrySet().iterator(); var5.hasNext(); ++i) {
                    Entry<Integer, String> entry = (Entry)var5.next();
                    param.put(entry.getValue(), args[(Integer)entry.getKey()]);
                    String genericParamName = "param" + (i + 1);
                    if (!this.names.containsValue(genericParamName)) {
                        param.put(genericParamName, args[(Integer)entry.getKey()]);
                    }
                }

                return param;
            }
        } else {
            return null;
        }
    }

(@Param("id")Integer id,@Param("lastName")String lastName);
//1、names:{0=id, 1=lastName};构造器的时候就确定好了

确定流程:
    1.获取每个标了param注解的参数的@Param的值:id,lastName;  赋值给name;
    2.每次解析一个参数给map中保存信息:(key:参数索引,value:name的值)
        name的值:
            标注了param注解:注解的值
            没有标注:
                1.全局配置:useActualParamName(jdk1.8):name=参数名
                2.name=map.size();相当于当前元素的索引
    {0=id, 1=lastName,2=2}
     

args【1,"Tom",'hello'】:

public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    //1、参数为null直接返回
    if (args == null || paramCount == 0) {
      return null;
     
    //2、如果只有一个元素,并且没有Param注解;args[0]:单个参数直接返回
    } else if (!hasParamAnnotation && paramCount == 1) {
      return args[names.firstKey()];
      
    //3、多个元素或者有Param标注
    } else {
      final Map<String, Object> param = new ParamMap<Object>();
      int i = 0;
      
      //4、遍历names集合;{0=id, 1=lastName,2=2}
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
      
          //names集合的value作为key;  names集合的key又作为取值的参考args[0]:args【1,"Tom"】:
          //eg:{id=args[0]:1,lastName=args[1]:Tom,2=args[2]}
        param.put(entry.getValue(), args[entry.getKey()]);
        
        
        // add generic param names (param1, param2, ...)param
        //额外的将每一个参数也保存到map中,使用新的key:param1...paramN
        //效果:有Param注解可以#{指定的key},或者#{param1}
        final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
        // ensure not to overwrite parameter named with @Param
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
  }
}

4.参数处理

参数值的获取
#{}:可以获取map中的值或者pojo对象属性的值;
${}:可以获取map中的值或者pojo对象属性的值;

演示:select * from tbl_employee where id=${id} and last_name=#{lastName}
效果:Preparing: select * from tbl_employee where id=2 and last_name=?

区别:
        #{}:是以预编译的形式,将参数设置到sql语句中;类似元素JDBC的PreparedStatement;防止sql注入
        ${}:取出的值直接拼装在sql语句中;会有SQL注入安全问题;大多情况下,我们取参数的值都应该去使用#{};
        原生jdbc不支持占位符的地方我们就可以使用${}进行取值
        比如分表、排序。。。;按照年份分表拆分
            select * from ${year}_salary where xxx;//年份可变
            select * from tbl_employee order by ${f_name} ${order}//排序按照的字段

 	<!-- public Employee getEmpByMap(Map<String, Object> map); -->
 	<select id="getEmpByMap" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from ${tableName} where id=${id} and last_name=#{lastName}
 	</select>
try{
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			//Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
			Map<String, Object> map = new HashMap<>();
			map.put("id", 2);
			map.put("lastName", "Tom");
			map.put("tableName", "tbl_employee");
			Employee employee = mapper.getEmpByMap(map);
}

#{}:更丰富的用法:
参数位置支持的属性:
    javaType、 jdbcType、 mode(存储过程)、 numericScale、resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能);

jdbcType通常需要在某种特定的条件下被设置:
        在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle(报错),如在oracle数据库中添加

EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//测试添加,邮箱的字段为空
Employee employee = new Employee(null, "jerry4",null, "1");

报错:JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生Jdbc的OTHER类型,oracle不能正确处理;
由于全局配置中:jdbcTypeForNull=OTHER;oracle不支持;两种办法
  1、#{email,jdbcType=OTHER};
  2、jdbcTypeForNull=NULL 改全局配置
      <setting name="jdbcTypeForNull" value="NULL"/>

5.select元素

• Select元素来定义查询操作。
• Id:唯一标识符。
  – 用来引用这条语句,需要和接口的方法名一致
• parameterType:参数类型。
  – 可以不传,MyBatis会根据TypeHandler自动推断
• resultType:返回值类型。
  – 别名或者全类名,如果返回的是集合,定义集合中元素的类型。不能和resultMap同时使用

 返回List

	<!-- public List<Employee> getEmpsByLastNameLike(String lastName); -->
	<!--resultType:如果返回的是一个集合,要写集合中元素的类型  -->
	<select id="getEmpsByLastNameLike" resultType="com.atguigu.mybatis.bean.Employee">
		select * from tbl_employee where last_name like #{lastName}
	</select>
List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
for (Employee employee : like) {
    System.out.println(employee);
}

单条记录封装map

//返回一条记录的map集合,key就是列名,值就是对应的值
public Map<String, Object> getEmpByIdReturnMap(Integer id);
 	<!--public Map<String, Object> getEmpByIdReturnMap(Integer id);  -->
 	<select id="getEmpByIdReturnMap" resultType="map">
 		select * from tbl_employee where id=#{id}
 	</select>
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
System.out.println(map);

 查询结果:

{gender=0, last_name=jerr, id=1, email=jerry@email}

多条记录封装map

//多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
@MapKey("lastName")
public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);
<!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);  -->
<select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
	select * from tbl_employee where last_name like #{lastName}
</select>
Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
System.out.println(map);

6.自动映射

当自动映射查询结果时,MyBatis 会获取结果中返回的列名并在 Java 类中查找相同名字的属性(忽略大小写)。 这意味着如果发现了 ID 列和 id 属性,MyBatis 会将列 ID 的值赋给 id 属性。

• 1、全局setting设置
  – autoMappingBehavior默认是PARTIAL,开启自动映射的功能。唯一的要求是列名和javaBean属性名一致
  – 如果autoMappingBehavior设置为null则会取消自动映射
  – 数据库字段命名规范,POJO属性符合驼峰命名法,如A_COLUMN---aColumn,我们可以开启自动驼峰命名规则映射功能,mapUnderscoreToCamelCase=true。

7.自定义规则resultMap

自定义resultMap,实现高级结果集映射。

示例

EmployeeMapperPlus.java

public interface EmployeeMapperPlus {
	
	public Employee getEmpById(Integer id);
	
	public Employee getEmpAndDept(Integer id);
	
	public Employee getEmpByIdStep(Integer id);
	
	public List<Employee> getEmpsByDeptId(Integer deptId);

}

EmployeeMapperPlus.xml

	<!--自定义某个javaBean的封装规则
	type:自定义规则的Java类型
	id:唯一id,方便引用
	  -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
		<!--指定主键列的封装规则
		id定义主键,底层会有优化;
		column:指定哪一列
		property:指定对应的javaBean属性
		  -->
		<id column="id" property="id"/>

		<!-- 定义普通列封装规则 -->
		<result column="last_name" property="lastName"/>
		<!-- 其他不指定的列会自动封装.我们只要写resultMap就把全部的映射规则都写上(便于检查)。 -->
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	</resultMap>
		
    <!-- resultMap:自定义结果集映射规则;  -->
	<!-- public Employee getEmpById(Integer id); -->
	<select id="getEmpById"  resultMap="MySimpleEmp">
		select * from tbl_employee where id=#{id}
	</select>

test

EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee empById = mapper.getEmpById(1);
System.out.println(empById);

8.resultMap关联查询

环境搭建

场景一:
查询Employee的同时查询员工对应的部门
一个员工有与之对应的部门信息

employee.java

public class Employee {
	
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	private Department dept;
    ......
}

department.java

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
    ... ...
}

tbl_dept

CREATE TABLE tbl_dept(
	id INT(11) PRIMARY KEY AUTO_INCREMENT,
	dept_name VARCHAR(255)
)

 修改tbl_empolyee

ALTER TABLE tbl_employee ADD COLUMN d_id INT(11);
ALTER TABLE tbl_employee ADD CONSTRAINT fk_emp_dept FOREIGN KEY(d_id) REFERENCES tbl_dept(id);

有两个封装结果的方法: 

单个对象级联属性封装

	<!--
		联合查询:级联属性封装结果集
	  -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp">
		<id column="id" property="id"/><!--主键列-->
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		<result column="did" property="dept.id"/><!--dept属性的id属性-->
		<result column="dept_name" property="dept.departmentName"/>
	</resultMap>
    	
<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp"><!--写resultType的话dept查不到值-->
		<!--会查出的列 id  last_name  gender    d_id     did  dept_name (private Department dept;)-->
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

test:

EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
//Employee empById = mapper.getEmpById(1);
Employee empAndDept = mapper.getEmpAndDept(1);
System.out.println(empAndDept);
System.out.println(empAndDept.getDept());

 association定义关联单个对象封装规则

    <!-- 
		使用association定义关联的单个对象的封装规则;
	 -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp2">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--  association可以指定联合的javaBean对象
		property="dept":指定哪个属性是联合的对象
		javaType:指定这个属性对象的类型[不能省略]
		-->
		<association property="dept" javaType="com.atguigu.mybatis.bean.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
	</resultMap>

 association分步查询

        1、先按照员工id查询员工信息
        2、根据查询员工信息中的d_id值去部门表查出部门信息
        3、部门设置到员工中

DepartmentMapper.java

import com.atguigu.mybatis.bean.Department;

public interface DepartmentMapper {
	
	public Department getDeptById(Integer id);

}

DepartmentMapper.xml

<!--public Department getDeptById(Integer id);  -->
	<select id="getDeptById" resultType="com.atguigu.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>

EmployeeMapper.xml

	 <!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- 关键步骤:association定义关联对象的封装规则
	 		select:表明当前属性是调用select指定的方法查出的结果
	 		column:指定将哪一列的值传给这个方法
	 		
	 		流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
	 	 -->
 		<association property="dept" 
	 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>

延迟加载:

上述操作,我们每次查询Employee对象的时候,部门信息都将一起查询出来。
                 部门信息在我们使用的时候再去查询;(按需加载)
                方法:在分段查询的基础之上加上两个配置

在全局配置文件中:

<!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>

collcetion定义关联集合封装规则

一个部门下有很多员工,查部门时显示该部门所有员工信息

场景二:
        查询部门的时候将部门对应的所有员工信息也查询出来:

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
    ... ...
}

departmentMapper.java

​
import com.atguigu.mybatis.bean.Department;

public interface DepartmentMapper {
	
	public Department getDeptById(Integer id);
	
	public Department getDeptByIdPlus(Integer id);

	public Department getDeptByIdStep(Integer id);
}

多对象结果级联查询 

 DepartmentMapper.xml

<!-- 	
	public class Department {
			private Integer id;
			private String departmentName;
			private List<Employee> emps;
	  did  dept_name  ||  eid  last_name  email   gender  
	 -->
	 
	<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则(association定义对象)
			ofType:指定集合里面元素的类型
            property:对应的javabean属性
		-->
		<collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
			<!-- 定义这个集合中元素的封装规则 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>
	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>

test:

DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
Department department = mapper.getDeptByIdPlus(1);
System.out.println(department);
System.out.println(department.getEmployees());

多对象结果collection分布查询&延迟查询

1.先根据部门id查部门信息

2.根据部门id查员工信息

3.员工信息设置到查询得到的部门信息中

EmployeeMapperPlus.java

public interface EmployeeMapperPlus {	
    ......
	public List<Employee> getEmpsByDeptId(Integer deptId);
}

EmployeeMapperPlus.xml 

	<!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
	<select id="getEmpsByDeptId" resultType="com.atguigu.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>

 DepartmentMapper.xml

<!-- collection:分段查询 -->
	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{id}" ></collection><!--id列的值传给select中的方法-->
	</resultMap>
	<!-- public Department getDeptByIdStep(Integer id); -->
	<select id="getDeptByIdStep" resultMap="MyDeptStep">
		select id,dept_name from tbl_dept where id=#{id}
	</select>

test: 

Department deptByIdStep = mapper.getDeptByIdStep(1);
System.out.println(deptByIdStep.getDepartmentName());
System.out.println(deptByIdStep.getEmples());

分布查询传递多列值: 

将多列的值封装map传递;
            column="{key1=column1,key2=column2}"

 fetchType="lazy":表示使用延迟加载;(这样使用的话就不用改全局设置)
                - lazy:延迟
                - eager:立即

	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>

discriminator鉴别器

鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
例子:封装Employee:
            如果查出的是女生:就把部门信息查询出来,否则不查询;
            如果是男生,把last_name这一列的值赋值给email;

	 <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmpDis">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!--
	 		column:指定判定的列名
	 		javaType:列值对应的java类型  -->
	 	<discriminator javaType="string" column="gender"><!--mybatis为所有java类型都起好了别名-->
	 		<!--女生  resultType:指定封装的结果类型;不能缺少。/resultMap-->
	 		<case value="0" resultType="com.atguigu.mybatis.bean.Employee">
	 			<association property="dept" 
			 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
			 		column="d_id">
		 		</association>
	 		</case>
	 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
	 		<case value="1" resultType="com.atguigu.mybatis.bean.Employee">
		 		<id column="id" property="id"/>
			 	<result column="last_name" property="lastName"/>
			 	<result column="last_name" property="email"/>
			 	<result column="gender" property="gender"/>
	 		</case>
	 	</discriminator>
	 </resultMap>

五、动态SQL

动态SQL是MyBatis强大特性之一,极大的简化我们拼装SQL的操作。
动态SQL元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。
MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作。

1.if

EmployeeMapperDynamicSQL.xml

	 <!-- 查询员工,要求,携带了哪个字段查询条件就带上这个字段的值 -->
	 <!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
	 <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- where --><!--使用下面的where标签,避免SQL格式封装问题-->
	 	<where>
		 	<!-- test:判断表达式(OGNL)
		 	OGNL使用官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	
		 	遇见特殊符号应该去写转义字符:
		 	&&:
		 	-->
		 	<if test="id!=null">
		 		id=#{id}
		 	</if>
		 	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;"><!--&&(and)的转义写法&amp;&amp;"的转义写法&quot;&quot;-->
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 	</where>
	 </select>

查询的时候如果某些条件没带可能sql拼装会有问题

如id没有参数值,得到的sql语句为select * from tbl_employee where  and last_name like ?
解决方法:1、给where后面加上1=1,以后的条件都and xxx.
                  2、mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
                注意:where只会去掉开头多出来的and或者or。

test:

@Test
	public void testDynamicSql() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			//select * from tbl_employee where id=? and last_name like ?
			//测试if\where
			Employee employee = new Employee(1, "Admin", null, null);
			List<Employee> emps = mapper.getEmpsByConditionIf(employee );
			for (Employee emp : emps) {
				System.out.println(emp);
			}
			
        }finally{
			openSession.close();
		}
	}

2.trim

自定义字符串截取,<where>标签不能解决语句后面多出的and或者or,如gender为空,则语句为

        <where>		 	
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		 email=#{email} and
		 	</if> 
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	</if>
	 	</where>

select * from tbl_employee where email =  ? and 

使用trim解决

 <!--public List<Employee> getEmpsByConditionTrim(Employee employee);  -->
	 <select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- 后面多出的and或者or where标签不能解决 
	 	prefix="":前缀:trim标签体中是整个字符串拼串后的结果。
	 			prefix给拼串后的整个字符串加一个前缀 
	 	prefixOverrides="":
	 			前缀覆盖: 去掉整个字符串前面多余的字符
	 	suffix="":后缀
	 			suffix给拼串后的整个字符串加一个后缀 
	 	suffixOverrides=""
	 			后缀覆盖:去掉整个字符串后面多余的字符
	 			
	 	-->
	 	<!-- 自定义字符串的截取规则 -->
	 	<trim prefix="where" suffixOverrides="and">
	 		<if test="id!=null">
		 		id=#{id} and
		 	</if>
		 	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		 		last_name like #{lastName} and
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		email=#{email} and
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	</if>
		 </trim>
	 </select>

3.choose

分支选择,只会进入一个条件查询。相当于带了break的swtich-case

	 <!-- public List<Employee> getEmpsByConditionChoose(Employee employee); -->
	 <select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee 
	 	<where>
	 		<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
	 		<choose>
	 			<when test="id!=null">
	 				id=#{id}
	 			</when>
	 			<when test="lastName!=null">
	 				last_name like #{lastName}
	 			</when>
	 			<when test="email!=null">
	 				email = #{email}
	 			</when>
	 			<otherwise>
	 				gender = 0<!--前面条件都不符合的情况查这个-->
	 			</otherwise>
	 		</choose>
	 	</where>
	 </select>

4.set

where封装查询条件, set封装修改条件

更新对应列的值

<!--public void updateEmp(Employee employee);  -->
	 <update id="updateEmp">
	 	<!-- Set标签的使用 -->
	 	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} 
     </update>

上述写法会出现多逗号的问题,如update tbl_employee set last_name=?, where id=?

通过set标签或trim改进,set标签会删掉额外的逗号

 <!--public void updateEmp(Employee employee);  -->
	 <update id="updateEmp">
	 	<!-- Set标签的使用 -->
	 	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} 
<!-- 		
		Trim:更新拼串
		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}  -->
	 </update>

5.for each

	 <!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids);  -->
	 <select id="getEmpsByConditionForeach" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!--
	 		collection:指定要遍历的集合:
	 			list类型的参数会特殊处理封装在map中,map的key就叫list
	 		item:将当前遍历出的元素赋值给指定的变量
	 		separator:每个元素之间的分隔符
	 		open:遍历出所有的结果拼接一个开始的字符
	 		close:遍历出所有的结果拼接一个结束的字符
	 		index:索引。遍历list的时候是index就是索引,item就是当前值
	 				      遍历map的时候index表示的就是map的key,item就是map的值
	 		
	 		#{变量名}就能取出变量的值也就是当前遍历出的元素
	 	  -->
	 	<foreach collection="ids" item="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	</foreach>
	 </select>

MySQL下for each批量插入的两种方式

方式一:

	 <!-- 批量保存 -->
	 <!--public void addEmps(@Param("emps")List<Employee> emps);  -->
	 <!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
	<insert id="addEmps">
	 	insert into tbl_employee(
	 		<include refid="insertColumn"></include>
	 	) 
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		</foreach>
	 </insert><!--   -->

test 

@Test
	public void testBatchSave() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			List<Employee> emps = new ArrayList<>();
			emps.add(new Employee(null, "smith0x1", "smith0x1@atguigu.com", "1",new Department(1)));
			emps.add(new Employee(null, "allen0x1", "allen0x1@atguigu.com", "0",new Department(1)));
			mapper.addEmps(emps);
			openSession.commit();
		}finally{
			openSession.close();
		}
	}
	

方式二: 

	 <!-- 这种方式需要数据库连接属性allowMultiQueries=true;(在一条语句中允许使用;来分隔多条查询)
	 <!--<property name="url" value="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true"/>-->
	 	这种分号分隔多个sql可以用于其他的批量操作(删除,修改) -->
	 <!-- <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下批量插入的两种方式

方式一:

1、多个insert放在begin - end;里面
begin
    insert into employees(employee_id,last_name,email) values(employees_seq.nextval,'test_001','test_001@atguigu.com');
    insert into employees(employee_id,last_name,email) values(employees_seq.nextval,'test_002','test_002@atguigu.com');
end;

 <insert id="addEmps" databaseId="oracle">
	 	<!-- 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> 

方式二:

2、利用中间表:
			insert into employees(employee_id,last_name,email)
		       select employees_seq.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
		       )

     <insert id="addEmps" databaseId="oracle">
<!-- oracle第二种批量方式  -->
	 	insert into employees(
	 		<!-- 引用外部定义的sql -->
	 		<include refid="insertColumn">
	 			<property name="testColomn" value="abc"/>
	 		</include>
	 	)
	 			<foreach collection="emps" item="emp" separator="union"
	 				open="select employees_seq.nextval,lastName,email from("
	 				close=")">
	 				select #{emp.lastName} lastName,#{emp.email} email from dual
	 			</foreach>
	 </insert>

6.内置参数

两个内置参数:
    不只是方法传递过来的参数可以被用来判断,取值。。。
    mybatis默认还有两个内置参数:
    _parameter:代表整个参数
        单个参数:_parameter就是这个参数
        多个参数:参数会被封装为一个map,_parameter就是代表这个map
     _databaseId:如果配置了databaseIdProvider标签,_databaseId就是代表当前数据库的别名,比如oracle

	  <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">	  	
	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null"><!--代表employee对象-->
	  				where last_name = #{_parameter.lastName}
	  			</if>
	  		</if>
	  		<if test="_databaseId=='oracle'">
	  			select * from employees
	  			<if test="_parameter!=null">
	  				where last_name = #{_parameter.lastName}
	  			</if>
	  		</if>
	  </select>

test

@Test
	public void testInnerParam() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			List<Employee> list = mapper.getEmpsTestInnerParameter(null);
			for (Employee employee : list) {
				System.out.println(employee);
			}
		}finally{
			openSession.close();
		}

7.bind绑定

bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 (创建一个变量,并将其绑定到当前的上下文)

	  <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
	  		<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
	  		<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 test="_databaseId=='oracle'">
	  			select * from employees
	  			<if test="_parameter!=null">
	  				where last_name like #{_lastName}
	  			</if>
	  		</if>
	  </select>

test中

@Test
	public void testInnerParam() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			Employee employee2 = new Employee();
			employee2.setLastName("e");//我们建议在这里就写%e%
			List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
			for (Employee employee : list) {
				System.out.println(employee);
			}
		}finally{
			openSession.close();
		}

8.抽取可重用sql片段

          抽取可重用的sql片段。方便后面引用 
          1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
          2、include来引用已经抽取的sql:
          3、include还可以自定义一些property,sql标签内部就能使用自定义的属性
                  include-property:取值的正确方式${prop},#{不能使用这种方式}


	  <sql id="insertColumn">
	  		<if test="_databaseId=='oracle'">
	  			employee_id,last_name,email
	  		</if>
	  		<if test="_databaseId=='mysql'">
	  			last_name,email,gender,d_id
	  		</if>
	  </sql>

<!-- oracle第二种批量方式  -->
	 	insert into employees(
	 		<!-- 引用外部定义的sql -->
	 		<include refid="insertColumn">
	 			<property name="testColomn" value="abc"/>
	 		</include>
	 	)
	 			<foreach collection="emps" item="emp" separator="union"
	 				open="select employees_seq.nextval,lastName,email from("
	 				close=")">
	 				select #{emp.lastName} lastName,#{emp.email} email from dual
	 			</foreach>
	

六、缓存机制

存在两级缓存:

一级缓存

一级缓存:(本地缓存):sqlSession级别的缓存。一级缓存是一直开启的,是SqlSession级别的一个Map,与数据库同一次会话期间查询到的数据会放在本地缓存中。以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;

        一级缓存失效情况(没有使用到当前一级缓存的情况,即还需要再向数据库发出查询):
        1、sqlSession不同。
        2、sqlSession相同,查询条件不同.(当前一级缓存中还没有这个数据)
        3、sqlSession相同,两次查询之间执行了增删改操作(这次增删改可能对当前数据有影响)
        4、sqlSession相同,手动清除了一级缓存(缓存清空)

@Test
	public void testFirstLevelCache() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			Employee emp01 = mapper.getEmpById(1);
			System.out.println(emp01);
			
			//xxxxx
			//1、sqlSession不同。
			//SqlSession openSession2 = sqlSessionFactory.openSession();
			//EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
			
			//2、sqlSession相同,查询条件不同
			
			//3、sqlSession相同,两次查询之间执行了增删改操作(这次增删改可能对当前数据有影响)
			//mapper.addEmp(new Employee(null, "testCache", "cache", "1"));
			//System.out.println("数据添加成功");
			
			//4、sqlSession相同,手动清除了一级缓存(缓存清空)
			//openSession.clearCache();
			
			Employee emp02 = mapper.getEmpById(1);
			//Employee emp03 = mapper.getEmpById(3);
			System.out.println(emp02);
			//System.out.println(emp03);
			System.out.println(emp01==emp02);
			
			//openSession2.close();
		}finally{
			openSession.close();
		}
	}

二级缓存

二级缓存:(全局缓存):基于namespace级别的缓存:一个namespace对应一个二级缓存:
        工作机制:
        1、一个会话,查询一条数据,这个数据就会被放在当前会话的一级缓存中;
        2、如果会话关闭;一级缓存中的数据会被保存到二级缓存中;新的会话查询信息,就可以参照二级缓存中的内容;
        3、sqlSession=查找=EmployeeMapper==>Employee
                                           DepartmentMapper===>Department
        不同namespace查出的数据会放在自己对应的缓存中(map)
        效果:数据会从二级缓存中获取
                查出的数据都会被默认先放在一级缓存中。只有会话提交或者关闭以后,一级缓存中的数据才会转移到二级缓存中
        使用:
            1)、开启全局二级缓存配置:<setting name="cacheEnabled" value="true"/>
            2)、去mapper.xml中配置使用二级缓存:
                <cache></cache>
            3)、我们的POJO需要实现序列化接口

<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
	<!-- <cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"></cache> -->
	<!--  
	eviction:缓存的回收策略:
		• LRU – 最近最少使用的:移除最长时间不被使用的对象。
		• FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
		• SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
		• WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
		• 默认的是 LRU。
	flushInterval:缓存刷新间隔
		缓存多长时间清空一次,默认不清空,设置一个毫秒值
	readOnly:是否只读:
		true:只读;mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。
				 mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,速度快
		false:非只读:mybatis觉得从缓存中获取的数据可能会被修改。
				mybatis会利用序列化&反序列的技术克隆一份新的数据给你。安全,速度慢
	size:缓存存放多少元素;
	type="":指定自定义缓存的全类名;
			实现Cache接口即可;
	-->
public class Employee implements Serializable{

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String lastName;
    ... ...
}

测试:

@Test
	public void testSecondLevelCache() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		SqlSession openSession2 = sqlSessionFactory.openSession();
		try{
			//1、两次会话查询同一个数据
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
			
			//第一个会话查完后关闭
			Employee emp01 = mapper.getEmpById(1);
			System.out.println(emp01);
			openSession.close();
			
			//第二次查询是从二级缓存中拿到的数据,并没有发送新的sql
			
			//如果没有开启二级缓存,会发起两次查询
			Employee emp02 = mapper2.getEmpById(1);
			System.out.println(emp02);
			openSession2.close();
			
		}finally{
			
		}
	}

和缓存有关的设置/属性:
            1)、cacheEnabled=true:(开启二级缓存)false:关闭缓存(二级缓存关闭)(一级缓存一直可用的)

            2)、每个select标签都有useCache标签,useCache="true":(使用二级缓存)
                    false:不使用缓存(一级缓存依然使用,二级缓存不使用)

            3)、【每个增删改标签的:flushCache="true":(一级二级都会清除)】,增删改执行完成后就会清除缓存;
                    测试:flushCache="true":一级缓存就清空了;二级也会被清除;
                    查询标签:flushCache="false":默认false,不清缓存
                    如果flushCache=true;每次查询之后都会清空缓存;缓存是没有被使用的;

            4)、sqlSession.clearCache();只是清除当前session的一级缓存;

            5)、localCacheScope:本地缓存作用域:(一级缓存SESSION);当前会话的所有数据保存在会话缓存中;
                      STATEMENT:数据不保存在缓存中,相当于可以禁用一级缓存;        

缓存原理图示

第三方缓存整合

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
MyBatis定义了Cache接口方便我们进行自定义扩展。
    步骤:
        – 1、导入ehcache包,以及整合包,日志包ehcache-core-2.6.8.jar、mybatis-ehcache-1.0.3.jar(ehcahce和mybatis的适配包)  slf4j-api-1.6.1.jar、slf4j-log4j12-1.6.2.jar
        – 2、编写ehcache.xml配置文件
        – 3、配置cache标签

EmployeeMapper.xml中

<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
	<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>    
    ......
</mapper>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 <!-- 磁盘保存路径 -->
 <diskStore path="D:\44\ehcache" />
 
 <defaultCache 
   maxElementsInMemory="10000" 
   maxElementsOnDisk="10000000"
   eternal="false" 
   overflowToDisk="true" 
   timeToIdleSeconds="120"
   timeToLiveSeconds="120" 
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU">
 </defaultCache>
</ehcache>
 
<!-- 
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
 
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目 
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
 
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
 diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
 -->

参照缓存:若想在命名空间中共享相同的缓存配置和实例。可以使用 cache-ref 元素来引用另外一个缓存。

DepartmentMapper.xml 

<!-- 引用缓存:namespace:指定和哪个名称空间下的缓存一样 -->
	<cache-ref namespace="com.atguigu.mybatis.dao.EmployeeMapper"/>

七、MyBatis-Spring整合

此部分使用IDEA进行SSM整合,会单独开辟专题。

八、MyBatis-逆向工程

MyBatis Generator

正常工程:根据数据表自己创建对应的Javabean,mapper接口等。

逆向:

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写
• 官方文档地址
http://www.mybatis.org/generator/
• 官方工程地址
https://github.com/mybatis/generator/releases下载jar包mybatis-generator-core-1.3.2.jar

MBG使用

• 使用步骤:
– 1)编写MBG的配置文件(重要几处配置)
1)jdbcConnection配置数据库连接信息
2)javaModelGenerator配置javaBean的生成策略
3)sqlMapGenerator 配置sql映射文件生成策略
4)javaClientGenerator配置Mapper接口的生成策略
5)table 配置要逆向解析的数据表
        tableName:表名
        domainObjectName:对应的javaBean名

mbg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

	<!-- 
		targetRuntime="MyBatis3Simple":生成简单版的CRUD
		MyBatis3:豪华版,能带查询条件
	 -->
  <context id="DB2Tables" targetRuntime="MyBatis3"><!--指定代码生成器的运行环境-->
  	<!-- jdbcConnection:指定如何连接到目标数据库 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true"
        userId="root"
        password="123456">
    </jdbcConnection>

	<!--  -->
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

	<!-- javaModelGenerator:指定javaBean的生成策略 
	targetPackage="":目标包名
	targetProject="":目标工程
	-->
    <javaModelGenerator targetPackage="com.atguigu.mybatis.bean" 
    		targetProject=".\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

	<!-- sqlMapGenerator:sql映射生成策略: -->
    <sqlMapGenerator targetPackage="com.atguigu.mybatis.dao"  
    	targetProject=".\conf">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

	<!-- javaClientGenerator:指定mapper接口所在的位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.dao"  
    	targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

	<!-- 指定要逆向分析哪些表:根据表要创建javaBean -->
    <table tableName="tbl_dept" domainObjectName="Department"></table>
    <table tableName="tbl_employee" domainObjectName="Employee"></table>
  </context>
</generatorConfiguration>

– 2)运行代码生成器生成代码
• 注意:
Context标签
targetRuntime=“MyBatis3“可以生成带条件的增删改查
targetRuntime=“MyBatis3Simple“可以生成基本的增删改查
如果再次生成,建议将之前生成的数据删除,避免xml向后追加内容出现的问
题。

生成

@Test
	public void testMbg() throws Exception {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		File configFile = new File("mbg.xml");
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
				callback, warnings);
		myBatisGenerator.generate(null);
	}

测试豪华版:

@Test
	public void testMyBatis3() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			//xxxExample就是封装查询条件的
			//1、查询所有
			//List<Employee> emps = mapper.selectByExample(null);
			
            //2、查询员工名字中有e字母并且员工性别是1的
			//封装员工查询条件的example
			EmployeeExample example = new EmployeeExample();
			//创建一个Criteria,这个Criteria就是拼装查询条件
			//select id, last_name, email, gender, d_id from tbl_employee 
			//WHERE ( last_name like ? and gender = ? ) or email like "%e%"
			Criteria criteria = example.createCriteria();
			criteria.andLastNameLike("%e%");
			criteria.andGenderEqualTo("1");
			
			Criteria criteria2 = example.createCriteria();
			criteria2.andEmailLike("%e%");
			example.or(criteria2);
			
			List<Employee> list = mapper.selectByExample(example);
			for (Employee employee : list) {
				System.out.println(employee.getId());
			}
			
		}finally{
			openSession.close();
		}
	}

九、MyBatis工作原理

 1、获取sqlSessionFactory对象:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 1.我们最初调用的build
public SqlSessionFactory build(InputStream inputStream) {
	//调用了重载方法
    return build(inputStream, null, null);
  }

// 2.调用的重载方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //  XMLConfigBuilder是专门解析mybatis的配置文件的类
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //这里又调用了一个重载方法。parser.parse()的返回值是Configuration对象
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } //省略部分代码
  }

下面进入对配置文件解析部分:

//在创建XMLConfigBuilder时,它的构造方法中解析器XPathParser已经读取了配置文件
//3. 进入XMLConfigBuilder 中的 parse()方法。
public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    //parser是XPathParser解析器对象,读取节点内数据,<configuration>是MyBatis配置文件中的顶层标签
    parseConfiguration(parser.evalNode("/configuration"));
    //最后返回的是Configuration 对象
    return configuration;
}

//4. 进入parseConfiguration方法
//此方法中读取了各个标签内容并封装到Configuration中的属性中。
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
}

到此对xml配置文件的解析就结束了(下文会对部分解析做详细介绍),回到步骤 2. 中调用的重载build方法。

// 5. 调用的重载方法
public SqlSessionFactory build(Configuration config) {
	//创建了DefaultSqlSessionFactory对象,传入Configuration对象。
    return new DefaultSqlSessionFactory(config);
  }
SqlSessionFactoryBuilder.java 
   public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        SqlSessionFactory var5;
        try {
            XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
            var5 = this.build(parser.parse());
        } catch (Exception var14) {
            throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
        } finally {
            ErrorContext.instance().reset();

            try {
                inputStream.close();
            } catch (IOException var13) {
            }

        }

        return var5;
    }

    public SqlSessionFactory build(Configuration config) {
        return new DefaultSqlSessionFactory(config);
    }

Configuration对象保存了所有配置文件的详细信息,包括全局配置文件和SQL映射文件。 

 mappedstatement:每一个方法对应一个MapperStatement对象。每一个MapperStatement对象代表一个增删改查标签,标签id表示

knownMapper:保存了每一个接口对应的MapperProxyFactory

2、获取sqlSession对象

    返回一个DefaultSQlSession对象,包含Executor和Configuration;这一步会创建Executor对象;

SqlSession openSession = sqlSessionFactory.openSession();

DefaultSqlSessionFactory.java 

   public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
        return this.openSessionFromDataSource(execType, (TransactionIsolationLevel)null, autoCommit);
    }

 private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
        Transaction tx = null;

        DefaultSqlSession var8;
        try {
            Environment environment = this.configuration.getEnvironment();
            TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
            tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            Executor executor = this.configuration.newExecutor(tx, execType);
            var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
        } catch (Exception var12) {
            this.closeTransaction(tx);
            throw ExceptionFactory.wrapException("Error opening session.  Cause: " + var12, var12);
        } finally {
            ErrorContext.instance().reset();
        }

        return var8;
    }
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        executorType = executorType == null ? this.defaultExecutorType : executorType;
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
        Object executor;
        if (ExecutorType.BATCH == executorType) {
            executor = new BatchExecutor(this, transaction);
        } else if (ExecutorType.REUSE == executorType) {
            executor = new ReuseExecutor(this, transaction);
        } else {
            executor = new SimpleExecutor(this, transaction);
        }

        if (this.cacheEnabled) {
            executor = new CachingExecutor((Executor)executor);
        }

        Executor executor = (Executor)this.interceptorChain.pluginAll(executor);
        return executor;
    }

  3、获取接口的代理对象(MapperProxy)

        getMapper,使用MapperProxyFactory创建一个MapperProxy的代理对象
        代理对象里面包含了,DefaultSqlSession(Executor)(能进行代理对象)

EmployeeMapper mapper = openSession.getMapper(xxxMapper.class);

public <T> T getMapper(Class<T> type) {
        return this.configuration.getMapper(type, this);
    }

 MapperRegistry.java

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }

4、执行增删改查方法

总结:

1、根据配置文件(全局,sql映射)初始化出Configuration对象
2、创建一个DefaultSqlSession对象,里面包含Configuration以及Executor(根据全局配置文件中的defaultExecutorType创建出对应的Executor)
3、DefaultSqlSession.getMapper():拿到Mapper接口对应的MapperProxy;
4、MapperProxy里面有(DefaultSqlSession);
5、执行增删改查方法:
        1)、调用DefaultSqlSession的增删改查(Executor);
        2)、会创建一个StatementHandler对象。(同时也会创建出ParameterHandler和ResultSetHandler)
        3)、调用StatementHandler预编译参数以及设置参数值;使用ParameterHandler来给sql设置参数
        4)、调用StatementHandler的增删改查方法;
        5)、ResultSetHandler封装结果
注意:
     四大对象每个创建的时候都有一个interceptorChain.pluginAll(parameterHandler);

十、插件开发

插件原理

    在四大对象创建的时候
    1、每个创建出来的对象不是直接返回的,而是调用interceptorChain.pluginAll(parameterHandler)方法
    2、获取到所有的Interceptor(拦截器)(插件需要实现的接口);
            调用interceptor.plugin(target);返回target包装后的对象
    3、插件机制,我们可以使用插件为目标对象创建一个代理对象;AOP(面向切面)
            我们的插件可以为四大对象创建出代理对象;
            代理对象就可以拦截到四大对象的每一个执行方法

blic Object pluginAll(Object target) {
	  for (Interceptor interceptor : interceptors) {
	    target = interceptor.plugin(target);
	  }
	  return target;
	}

插件编写

    1、编写Interceptor的实现类
    2、使用@Intercepts注解完成插件签名
    3、将写好的插件注册到全局配置文件中<plugin></plugin>

二、M
/**
 * 完成插件签名:
 *		告诉MyBatis当前插件用来拦截哪个对象的哪个方法
 */
@Intercepts(
		{
			@Signature(type=StatementHandler.class,method="parameterize",args=java.sql.Statement.class)
		})
public class MyFirstPlugin implements Interceptor{

	/**
	 * intercept:拦截:
	 * 		拦截目标对象的目标方法的执行;
	 */
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("MyFirstPlugin...intercept:"+invocation.getMethod());
		//动态的改变一下sql运行的参数:以前1号员工,实际从数据库查询3号员工
		Object target = invocation.getTarget();
		System.out.println("当前拦截到的对象:"+target);
		//拿到:StatementHandler==>ParameterHandler===>parameterObject
		//拿到target的元数据
		MetaObject metaObject = SystemMetaObject.forObject(target);
		Object value = metaObject.getValue("parameterHandler.parameterObject");
		System.out.println("sql语句用的参数是:"+value);
		//修改完sql语句要用的参数
		metaObject.setValue("parameterHandler.parameterObject", 11);
		//执行目标方法
		Object proceed = invocation.proceed();
		//返回执行后的返回值
		return proceed;
	}

	/**
	 * plugin:
	 * 		包装目标对象的:包装:为目标对象创建一个代理对象
	 */
	@Override
	public Object plugin(Object target) {
		// TODO Auto-generated method stub
		//我们可以借助Plugin的wrap方法来使用当前Interceptor包装我们目标对象
		System.out.println("MyFirstPlugin...plugin:mybatis将要包装的对象"+target);
		Object wrap = Plugin.wrap(target, this);
		//返回为当前target创建的动态代理
		return wrap;
	}

	/**
	 * setProperties:
	 * 		将插件注册时 的property属性设置进来
	 */
	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
		System.out.println("插件配置的信息:"+properties);
	}

}
yBatis-HelloWorld
PageHelper插件进行分页
PageHelper是MyBatis中非常方便的第三方分页 插件。
官方文档: https://github.com/pagehelper/Mybatis
                    PageHelper/blob/master/README_zh.md
我们可以对照官方文档的说明,快速的使用插件

使用步骤

1、导入相关包 pagehelper-x.x.x.jar jsqlparse 0.9.5.jar
2、在MyBatis全局配置文件中配置分页插件。
3、使用PageHelper提供的方法进行分页
4、可以使用更强大的PageInfo封装返回结果
@Test
	public void test01() throws IOException {
		// 1、获取sqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		// 2、获取sqlSession对象
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			Page<Object> page = PageHelper.startPage(1, 5);//起始页码,每页记录数
			
			List<Employee> emps = mapper.getEmps();
			//传入要连续显示多少页
			PageInfo<Employee> info = new PageInfo<>(emps, 5);//连续显示5页所呈现的页数
			for (Employee employee : emps) {
				System.out.println(employee);
			}
			/*System.out.println("当前页码:"+page.getPageNum());
			System.out.println("总记录数:"+page.getTotal());
			System.out.println("每页的记录数:"+page.getPageSize());
			System.out.println("总页码:"+page.getPages());*/
			///xxx
			System.out.println("当前页码:"+info.getPageNum());
			System.out.println("总记录数:"+info.getTotal());
			System.out.println("每页的记录数:"+info.getPageSize());
			System.out.println("总页码:"+info.getPages());
			System.out.println("是否第一页:"+info.isIsFirstPage());
			System.out.println("连续显示的页码:");
			int[] nums = info.getNavigatepageNums();
			for (int i = 0; i < nums.length; i++) {
				System.out.println(nums[i]);
			}
			
			
			//xxxx
		} finally {
			openSession.close();
		}

	}

三、MyBatis-全局配置文件
四、MyBatis-映射文件
六、MyBatis-缓存机制
七、MyBatis-Spring整合
八、MyBatis-逆向工程
九、MyBatis-工作原理
十、MyBatis-插件开发
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值