Mybatis学习完整版

跟着狂神的视频学习的!!! 笔记有误记得留言 !!!有什么问题也欢迎留言
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓以下是正文部分↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

Mybatis3

1.简介

环境说明:

  • jdk 8 +
  • MySQL 5.7.19
  • maven-3.6.1
  • IDEA

学习前需要掌握:

  • JDBC
  • MySQL
  • Java 基础
  • Maven
  • Junit

什么是MyBatis

  • MyBatis 是一款优秀的持久层框架
  • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
  • MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
  • MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。
  • 2013年11月迁移到Github .
  • Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
  • GitHub : https://github.com/mybatis/mybatis-3

持久化

持久化是将程序数据在持久状态和瞬时状态间转换的机制。

  • 即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中、XML数据文件中等等。
  • JDBC就是一种持久化机制。文件IO也是一种持久化机制。
  • 在生活中 : 将鲜肉冷藏,吃的时候再解冻的方法也是。将水果做成罐头的方法也是。

为什么需要持久化服务呢?那是由于内存本身的缺陷引起的

  • 内存断电后数据会丢失,但有一些对象是无论如何都不能丢失的,比如银行账号等,遗憾的是,人们还无法保证内存永不掉电。
  • 内存过于昂贵,与硬盘、光盘等外存相比,内存的价格要高2~3个数量级,而且维持成本也高,至少需要一直供电吧。所以即使对象不需要永久保存,也会因为内存的容量限制不能一直呆在内存中,需要持久化来缓存到外存。

持久层

什么是持久层?

  • 完成持久化工作的代码块 . ----> dao层 【DAO (Data Access Object) 数据访问对象】
  • 大多数情况下特别是企业级应用,数据持久化往往也就意味着将内存中的数据保存到磁盘上加以固化,而持久化的实现过程则大多通过各种关系数据库来完成。
  • 不过这里有一个字需要特别强调,也就是所谓的“层”。对于应用系统而言,数据持久功能大多是必不可少的组成部分。也就是说,我们的系统中,已经天然的具备了“持久层”概念?也许是,但也许实际情况并非如此。之所以要独立出一个“持久层”的概念,而不是“持久模块”,“持久单元”,也就意味着,我们的系统架构中,应该有一个相对独立的逻辑层面,专注于数据持久化逻辑的实现.
  • 与系统其他部分相对而言,这个层面应该具有一个较为清晰和严格的逻辑边界。【说白了就是用来操作数据库存在的!】

为什么需要Mybatis

  • Mybatis就是帮助程序猿将数据存入数据库中 , 和从数据库中取数据 .

  • 传统的jdbc操作 , 有很多重复代码块 .比如 : 数据取出时的封装 , 数据库的建立连接等等… , 通过框架可以减少重复代码,提高开发效率 .

  • MyBatis 是一个半自动化的ORM框架 (Object Relationship Mapping) -->对象关系映射

  • 所有的事情,不用Mybatis依旧可以做到,只是用了它,所有实现会更加简单!技术没有高低之分,只有使用这个技术的人有高低之别

  • MyBatis的优点

    • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
    • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 提供xml标签,支持编写动态sql。
  • 最重要的一点,使用的人多!公司需要!

2.第一个Mybatis程序

思路流程:搭建环境–>导入Mybatis—>编写代码—>测试

代码演示

1、搭建实验数据库

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2、导入MyBatis相关 jar 包

  • GitHub上找
<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

3、编写MyBatis核心配置文件

  • 查看帮助文档
<?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>
    <!-- 配置mybatis的环境 -->
   <environments default="development">
       <!-- 配置mysql的环境 -->
       <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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
               <property name="username" value="root"/>
               <property name="password" value="123456"/>
           </dataSource>
       </environment>
   </environments>
    <!-- 告知mybatis映射配置的位置 -->
   <mappers>
       <mapper resource="com/kuang/dao/userMapper.xml"/>
   </mappers>
</configuration>

4、编写MyBatis工具类

  • 查看帮助文档
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

   private static SqlSessionFactory sqlSessionFactory;

   static {
       try {
           //1.读取配置文件
           //2.SQLSession工厂
           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
           e.printStackTrace();
      }
  }

   //获取SqlSession连接
   public static SqlSession getSession(){
       return sqlSessionFactory.openSession();
  }

}

5、创建实体类

public class User {
   
   private int id;  //id
   private String name;   //姓名
   private String pwd;   //密码
   
   //构造,有参,无参
   //set/get
   //toString()
   
}

6、编写Mapper接口类

import com.kuang.pojo.User;
import java.util.List;

public interface UserMapper {
   List<User> getUserList();
}

7、编写Mapper.xml配置文件

  • namespace 十分重要,不能写错!
<?xml version="1.0" encoding="UTF-8" ?>
<!--编写Mapper.xml配置文件-->
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UserMapper">
 <select id="selectUser" resultType="com.kuang.pojo.User">
  select * from user
 </select>
</mapper>
namespace   -->对象的映射的接口
id			-->对应接口的方法
resiltType	-->把结果封装对象类型

8、编写测试类

  • Junit 包测试
public class MyTest {
   @Test
   public void getUserList() {
       //创建我们的实现接口的对象
       SqlSession session = MybatisUtils.getSession();
       
       //调用对应的方法
       //方法一:(淘汰)
       //List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserList");
       //方法二:
       UserMapper mapper = session.getMapper(UserMapper.class);
       List<User> users = mapper.getUserList();

       //处理结果
       for (User user: users){
           System.out.println(user);
      }
       //关闭
       session.close();
  }
}

9、运行测试,成功的查询出来的我们的数据,ok!

问题说明

1. 可能出现问题说明:在mybatis核心配置文件里的位置写错

//java.lang.ExceptionInInitializerError
<!-- 告知mybatis映射配置的位置 -->
    <mappers>
        <mapper resource="com/chen/dao/userMapper.xml"/>
    </mappers>

2. 可能出现问题说明:在测试包装类型过程中产生了一个错误!!!时区问题

在url设置时区为utc的时候用了小写,必须要大写

//org.apache.ibatis.exceptions.PersistenceException: 
//### Error querying database.  Cause: java.sql.SQLException: No timezone mapping entry for 'utc'
//### The error may exist in com/chen/dao/userMapper.xml
//### The error may involve com.chen.dao.UserMapper.selectUser
//### The error occurred while executing a query
//### Cause: java.sql.SQLException: No timezone mapping entry for 'utc'

//翻译:
//    org.apache.ibatis.exceptions.PersistenceException:查询数据库时出错。原因:java.sql.SQLException:“utc”没有时区映射条目 comchendaouserMapper.xml 中可能存在错误 该错误可能涉及 com.chen.dao.UserMapper.selectUser 执行查询时发生错误原因:java.sql。 SQLException: 没有“utc”的时区映射条目
<!--  在mybatis核心配置文件中url  -->
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC"/>

3. 可能出现问题说明:Maven静态资源过滤问题

<!--    在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

写在父类pom.xml里面

3.CRUD

CRUD操作

namespace

  1. 将上面案例中的UserMapper接口改名为 UserDao;
  2. 将UserMapper.xml中的namespace改为为UserDao的路径 .
  3. 再次测试

结论:

配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!

select

  • select标签是mybatis中最常用的标签之一

  • select语句有很多属性可以详细配置每一条SQL语句

    • SQL语句返回值类型。【完整的类名或者别名】
    • 传入SQL语句的参数类型 。【万能的Map,可以多尝试使用】
    • 命名空间中唯一的标识符
    • 接口中的方法名与映射文件中的SQL语句ID 一一对应
    • id
    • parameterType
    • resultType

需求:根据id查询用户

1、在UserMapper中添加对应方法

public interface UserMapper {
   //查询全部用户
   List<User> selectUser();
   //根据id查询用户
   User selectUserById(int id);
}

2、在UserMapper.xml中添加Select语句

<select id="selectUserById" resultType="com.kuang.pojo.User">
select * from user where id = #{id}
</select>

3、测试类中测试

@Test
public void tsetSelectUserById() {
   SqlSession session = MybatisUtils.getSession();  //获取SqlSession连接
   UserMapper mapper = session.getMapper(UserMapper.class);
   User user = mapper.selectUserById(1);
   System.out.println(user);
   session.close();
}

课堂练习:根据 密码 和 名字 查询用户

思路一:直接在方法中传递参数

1、在接口方法的参数前加 @Param属性

2、Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型

//通过密码和名字查询用户
User selectUserByNP(@Param("username") String username,@Param("pwd") String pwd);

/*
   <select id="selectUserByNP" resultType="com.kuang.pojo.User">
     select * from user where name = #{username} and pwd = #{pwd}
   </select>
*/

思路二:使用万能的Map

1、在接口方法中,参数直接传递Map;

User selectUserByNP2(Map<String,Object> map);

2、编写sql语句的时候,需要传递参数类型,参数类型为map

<select id="selectUserByNP2" parameterType="map" resultType="com.kuang.pojo.User">
	select * from user where name = #{username} and pwd = #{pwd}
</select>

3、在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!

Map<String, Object> map = new HashMap<String, Object>();
map.put("username","小明");
map.put("pwd","123456");
User user = mapper.selectUserByNP2(map);

总结:如果参数过多,我们可以考虑直接使用Map实现,如果参数比较少,直接传递参数即可

insert

我们一般使用insert标签进行插入操作,它的配置和select标签差不多!

需求:给数据库增加一个用户

1、在UserMapper接口中添加对应的方法

//添加一个用户
int addUser(User user);

2、在UserMapper.xml中添加insert语句

<insert id="addUser" parameterType="com.kuang.pojo.User">
    insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>

3、测试

@Test
public void testAddUser() {
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   User user = new User(5,"王五","zxcvbn");
   int i = mapper.addUser(user);
   System.out.println(i);
   session.commit(); //提交事务,重点!不写的话不会提交到数据库
   session.close();
}

注意点:增、删、改操作需要提交事务!

**
**

update

我们一般使用update标签进行更新操作,它的配置和select标签差不多!

需求:修改用户的信息

1、同理,编写接口方法

//修改一个用户
int updateUser(User user);

2、编写对应的配置文件SQL

<update id="updateUser" parameterType="com.kuang.pojo.User">
  update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>

3、测试

@Test
public void testUpdateUser() {
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   User user = mapper.selectUserById(1);
   user.setPwd("asdfgh");
   int i = mapper.updateUser(user);
   System.out.println(i);
   session.commit(); //提交事务,重点!不写的话不会提交到数据库
   session.close();
}

delete

我们一般使用delete标签进行删除操作,它的配置和select标签差不多!

需求:根据id删除一个用户

1、同理,编写接口方法

//根据id删除用户
int deleteUser(int id);

2、编写对应的配置文件SQL

<delete id="deleteUser" parameterType="int">
  delete from user where id = #{id}
</delete>

3、测试

@Test
public void testDeleteUser() {
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   int i = mapper.deleteUser(5);
   System.out.println(i);
   session.commit(); //提交事务,重点!不写的话不会提交到数据库
   session.close();
}

小结:

  • 所有的增删改操作都需要提交事务!
  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
  • 有时候根据业务的需求,可以考虑使用map传递参数!
  • 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!

思考题

模糊查询like语句该怎么写?

第1种:在Java代码中添加sql通配符。

string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);

<select id=”selectlike”>
select * from foo where bar like #{value}
</select>

第2种:在sql语句中拼接通配符,会引起sql注入

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);

<select id=”selectlike”>
    select * from foo where bar like "%"#{value}"%"
</select>

4.配置解析

1.核心配置文件

  • mybatis-config.xml 系统核心配置文件
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
  • 能配置的内容如下:

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

我们可以阅读 mybatis-config.xml 上面的dtd的头文件!

2.环境配置(environments)

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

配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行环境(通过default指定)

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

事务管理器(transactionManager)

(了解) 在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")

数据源(dataSource)

(了解) 有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")

学会使用配置多套运行环境

Mybaits默认的事务管理器就是JDBC , 连接池: POOLED

数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等…

3.属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。[db.properties]

在xml中,所有的标签都可以规定其顺序

在这里插入图片描述

第一步 ; 在资源目录下新建一个db.properties

driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username=root
pwd=123456

第二步 : 将文件导入properties 配置文件

在这里插入图片描述

以下是操作mybatis-config.xml在其中增加一些属性配置

<!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用过外部配置文件的!

在这里插入图片描述

4.类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
<!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.chen.pojo.User" alias="User"/>
    </typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

	<typeAliases>
        <package name="com.chen.pojo"/>
    </typeAliases>

注意:

  • 在实体类比较少的时候,使用第一种方式。
  • 如果实体类十分多,建议使用第二种。
  • 第一种可以DIY别名,第二种则·不行·

注解别名

@Alias("hello")
public class User {
......
}

优先级排行

直接配置到实体类别名>注解别名>配置到包名

<typeAlias type="com.chen.pojo.User" alias="User"/>
		优先于
@Alias("hello")
		优先于
<package name="com.chen.pojo"/>

5.设置(settings)

  • 设置(settings)相关 => 查看帮助文档
    • 懒加载
    • 日志实现
    • 缓存开启关闭
  • 一个配置完整的 settings 元素的示例如下:
<settings>
 <setting name="cacheEnabled" value="true"/>
 <setting name="lazyLoadingEnabled" value="true"/>
 <setting name="multipleResultSetsEnabled" value="true"/>
 <setting name="useColumnLabel" value="true"/>
 <setting name="useGeneratedKeys" value="false"/>
 <setting name="autoMappingBehavior" value="PARTIAL"/>
 <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
 <setting name="defaultExecutorType" value="SIMPLE"/>
 <setting name="defaultStatementTimeout" value="25"/>
 <setting name="defaultFetchSize" value="100"/>
 <setting name="safeRowBoundsEnabled" value="false"/>
 <setting name="mapUnderscoreToCamelCase" value="false"/>
 <setting name="localCacheScope" value="SESSION"/>
 <setting name="jdbcTypeForNull" value="OTHER"/>
 <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。

在这里插入图片描述

还有一个有可能会用到,可以把数据库的 last_name 变为 lastName

在这里插入图片描述

为什么数据库要用 last_name命名而不用lastName

因为Oracle编译后last_name变成了LASTNAME,可读性极低

6.其他配置(了解)

  • typeHandlers(类型处理器)
    • 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。
    • 你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。【了解即可】
  • objectFactory(对象工厂)
    • MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。
    • 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过有参构造方法来实例化。
    • 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。【了解即可】
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

7.映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件;

方式一:【推荐使用】

	<!--映射器 告知mybatis映射配置的位置 -->
	<mappers>
        <!-- 使用相对于类路径的资源引用 -->
        <mapper resource="com/chen/dao/userMapper.xml"/>
    </mappers>

方式二:使用class文件绑定注册

	<mappers>
        <!-- 使用映射器接口实现类的完全限定类名 -->
        <mapper class="com.chen.dao.UserMapper"/>
    </mappers>

注意点:

  • 接口和她的Mapper配置文件必须同名!
  • 接口和他的Mapper配置文件必须在同一个包下!

方式三:使用扫描包进行注入绑定

	<mappers>
        <!-- 将包内的映射器接口实现全部注册为映射器 -->
        <package name="com.chen.dao"/>
    </mappers>

注意:但是需要配置文件名称和接口名称一致,并且位于同一目录下

Mapper文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.mapper.UserMapper">
   <!--    查询所有-->
    <select id="getUserList" resultType="User">
        select * from user
    </select>
</mapper>
  • namespace中文意思:命名空间,作用如下:

    • namespace的命名必须跟某个接口同名
    • 接口中的方法与映射文件中sql语句id应该一一对应
    1. namespace和子元素的id联合保证唯一 , 区别不同的mapper
    2. 绑定DAO接口
    3. namespace命名规则 : 包名+类名

MyBatis 的真正强大在于它的映射语句,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 为聚焦于 SQL 而构建,以尽可能地为你减少麻烦。

8.生命周期和作用域

在这里插入图片描述

生命周期,和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题。

SqlSessionFactoryBuiler:

  • 作用在于创建 SqlSessionFactory, 一旦创建了SqlSessionFactory,就不再需要它了

  • SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域

  • 局部变量

SqlSessionFactory:

  • 说白了就是可以想象为︰数据库连接池
  • 你可以在一个事务里面执行多条 SQL,然后通过它的 commit、rollback 等方法,提交或者回滚事务。所以它应该存活在一个业务请求中,处理完整个请求后,应该关闭这条连接,让它归还给 SqlSessionFactory,否则数据库资源就很快被耗费精光,系统就会瘫痪,所以用 try…catch…finally… 语句来保证其正确关闭。
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
  • 因此SqlSessionFactory的最佳作用域是应用作用域

SqlSession:

  • 连接到连接池的一个请求!
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完之后需要赶紧关闭,否则资源被占用!

在这里插入图片描述

这里的每一个Mapper就代表一个具体的业务!


5.解决属性名和字段名不一样的问题

1.问题

数据库的字段

在这里插入图片描述

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {

  private long id;
  private String name;
  private String password;

测试出现问题

在这里插入图片描述

//		select * from user where id = #{id}
//类型处理器
//		select id ,name ,pwd from user where id = #{id}

解决方案:

	<select id="getUserById" parameterType="int" resultType="com.chen.pojo.User">
        select id ,name ,pwd as password from user where id = #{id}
    </select>

2.resultMap

结果集映射

int		name	pwd
int		name	password
<resultMap id="map" type="User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>

<!--    根据ID查询-->
    <select id="getUserById" resultMap="map">
        select * from user where id = #{id}
    </select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

6.日志

6.1日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!

曾经: sout 、debug

现在:日志工厂!

在这里插入图片描述

  • SLF4J
  • LOG4J【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING【掌握】
  • NO_LOGGING

在Mybatis中具体使用哪个日志实现,在设置中设定!

STDOUT_LOGGING 标准日志输出

在Mybatis核心配置文件中 ,配置我们的日志!

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

在这里插入图片描述

6.2 LOG4J 日志工厂

什么是Loganj?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

1.jar的依赖

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2.配置文件log4j.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和fiLe的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = system.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.patternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/chen.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3.配置log4j为日志的实现

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

4.log4j的使用! 直接运行刚才的查询

在这里插入图片描述

简单使用

1. 在要使用Log4j的类中导包	import org.apache.log4j.Logger;
2. 日志对象,参数为当前类的class
    static Logger logger = Logger.getLogger(MyTest.class)

3.日志级别

logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");

7.分页

思考:为什么要分页?

  • 减少数据的处理量

使用limit分页

//分页
List<User> getUserByLimit(Map<String, Integer> map);

配置

<!--    分页-->
<select id="getUserByLimit" parameterType="map" resultMap="map">
    select * from user limit #{startIndex},#{pageSize}
</select>

8.使用注解开发

面向接口编程

  • 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  • 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。

  • 接口的本身反映了系统设计人员对系统的抽象理解。

  • 接口应有两类:

    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
  • 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法 .

  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现 .

  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构

利用注解开发

  • mybatis最初配置信息是基于 XML ,映射语句(SQL)也是定义在 XML 中的。而到MyBatis 3提供了新的基于注解的配置。不幸的是,Java 注解的的表达力和灵活性十分有限。最强大的 MyBatis 映射并不能用注解来构建

  • sql 类型主要分成 :

    • @select ()
    • @update ()
    • @Insert ()
    • @delete ()

**注意:**利用注解开发就不需要mapper.xml映射文件了 .

1、我们在我们的接口中添加注解

//查询全部用户
@Select("select id,name,pwd password from user")
public List<User> getAllUser();

2、在mybatis的核心配置文件中注入

<!--使用class绑定接口-->
<mappers>
   <mapper class="com.kuang.mapper.UserMapper"/>
</mappers>

3、我们去进行测试

@Test
public void testGetAllUser() {
   SqlSession session = MybatisUtils.getSession();
   //本质上利用了jvm的动态代理机制
   UserMapper mapper = session.getMapper(UserMapper.class);

   List<User> users = mapper.getAllUser();
   for (User user : users){
       System.out.println(user);
  }

   session.close();
}

4、利用Debug查看本质

在这里插入图片描述

5、本质上利用了jvm的动态代理机制

在这里插入图片描述

6、Mybatis详细的执行流程

在这里插入图片描述

CRUD

首先在工具类里面设置一个自动提交事务

MybatisUtils

package com.chen.utils;
/*
 *@description:MyBatis工具类
 *@author:陈琰
 *@time:2021/8/31  12:48
 */

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //1.读取配置文件
            //2.SQLSession工厂
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession连接
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(true);
    }
}

最下面的原本为	return sqlSessionFactory.openSession(false);

UserMapper

package com.chen.dao;
import com.chen.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

//编写Mapper接口类
public interface UserMapper {
    //查询全部用户
    @Select("select * from user")
    List<User> getUserList();

    //模糊查询
    @Select("select * from user where name like #{value}")
    List<User> getUserLike(String value);

    //根据ID查询用户
    @Select("select * from user where id = #{id}")
    User getUserById(int id);

    //根据id和name查询------方法存在多个参数时候用@param,   #{id}的id是@Param("id")的id
    @Select("select * from user where id = #{id} and name = #{name}")
    User getUserByIdName(@Param("id") int id2,@Param("name") String name);

    //insert一个用户
    @Insert("insert into user(id,name,pwd) value(#{id},#{name},#{pwd})")
    int addUser(User user);

    //对象用insert一个用户map
    @Insert("insert into user(id,name,pwd) value(#{id},#{name},#{pwd})")
    int addUser2(Map<String, Object> map);

    //修改用户
    @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
    int updateUser(User user);

    //删除用户
    @Delete("delete from user where id=#{uid}")
    int deleteUser(@Param("uid") int id);
}

UserMapperTest


/*
 *@description:描述
 *@author:陈琰
 *@time:2021/9/2  18:58
 */

import com.chen.dao.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserMapperTest {

    private SqlSession sqlSession;
    private UserMapper mapper;

    @Before
    public void init(){
        sqlSession = MybatisUtils.getSession();
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void destroy(){
        sqlSession.close();
    }

    //查询全部用户
    @Test
    public void getUserList(){
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    //模糊查询
    @Test
    public void getUserLike(){
        List<User> c = mapper.getUserLike("%c%");
        for (User user : c) {
            System.out.println(user);
        }
    }

    //根据id查询
    @Test
    public void getUserById(){
        User user = mapper.getUserById(1);
        System.out.println(user);
    }

    //根据id和name查询
    @Test
    public void getUSerByIdName(){
        User cy = mapper.getUserByIdName(1, "cy");
        System.out.println(cy);
    }

    //添加用户
    @Test
    public void addUser(){
        mapper.addUser(new User(6,"爱因斯蛋","123456"));
    }

    //对象用万能的map添加用户
    @Test
    public void addUser2(){
        HashMap map = new HashMap<String,Object>();
        map.put("name","爱因斯蛋2");
        map.put("pwd","123");
        mapper.addUser2(map);
    }

    //修改对象信息
    @Test
    public void updateUser() {
        mapper.updateUser(new User(7,"阿蛋2","123"));
    }

    //删除用户
    @Test
    public void deleteUser(){
        mapper.deleteUser(3);
    }
}

9.Lombok

1.在Idea中下载插件

在这里插入图片描述

2.在pom.xml中导入jar包

<!--Lombok的坐标-->
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>

3.在实体类中直接使用注解@Date

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

自动生成了哪些方法呢?

在这里插入图片描述

我们需要注意的是这里面只有无参构造

无有参构造如果同时需要有参和无参需要加注解

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;
}

10.多对一处理

1.环境搭建

在这里插入图片描述

2.按照结果嵌套处理

<!--方法一:按照结果嵌套处理-->
<!--思路:
   1. 直接查询出结果,进行结果集的映射-->
    <select id="getStudentList" resultMap="StudentTeacher">
        select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
    </select>

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <!-- 复杂的属性,我们需要单独处理   对象:association   集合:collection
        对象中的    Javatype=""  指定属性的类型!
        集合中的泛型信息,我们使用ofType获取
        -->
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

3.按查询嵌套处理

<!--    方法二:
    思路:
    1.查询所有的学生信息
    2.根据查询出来的学生的tid,寻找对应的老师!子查询
-->

    <select id="getStudentList2" resultMap="StudentTeacher2">
        select * from student
    </select>

    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
<!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{tid}
    </select>

小结

按照查询进行嵌套处理就像SQL中的子查询

按照结果进行嵌套处理就像SQL中的联表查询

11.一对多处理

1.环境搭建

在这里插入图片描述

2.按照结果嵌套处理

<select id="getTeacher" resultMap="TeacherStudent">
        select t.id tid,t.name tname,s.id sid,s.name sname
        from teacher t,student s
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="tid" property="tid"/>
        </collection>
    </resultMap>

3.按查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId" />
    </resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid = #{tid}
    </select>

小结

1、关联-association

2、集合-collection

3、所以association是用于一对一和多对一,而collection是用于一对多的关系

4、JavaType和ofType都是用来指定对象类型的

  • JavaType是用来指定pojo中属性的类型
  • ofType指定的是映射到list集合属性中pojo的类型。

注意说明:

1、保证SQL的可读性,尽量通俗易懂

2、根据实际要求,尽量编写性能更高的SQL语句

3、注意属性名和字段不一致的问题

4、注意一对多和多对一 中:字段和属性对应的问题

5、尽量使用Log4j,通过日志来查看自己的错误


12.动态SQL

介绍

什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.

官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

  -------------------------------
  - if
  - choose (when, otherwise)
  - trim (where, set)
  - foreach
  -------------------------------

if 语句

BlogMapper接口

//    动态SQL查询
List<Blog> queryBlogIf(Map map);

BlogMapper.xml配置

<select id="queryBlogIf" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <if test="title!=null">
                and title like #{title}
            </if>
            <if test="author!=null">
                and author like #{author}
            </if>
            <if test="views!=null">
                and views > #{views}
            </if>
        </where>
    </select>

test

//动态SQL查询
    @Test
    public void queryBlogIf(){
        HashMap map = new HashMap();
        map.put("title","%s%");
//        map.put("author","狂神说");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

choose

接口

//    动态sql使用choose元素
    List<Blog> queryBlogChoose(Map map);

xml

<!--    使用choose    where\choose\when\otherwise -->
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from blog
        <where>
            <choose>
                <when test="title != null">
                    and title like #{title}
                </when>
                <when test="author!=null">
                    and author like #{author}
                </when>
                <otherwise>
                    and views > #{views}
                </otherwise>
            </choose>
        </where>
    </select>

test

//动态SQL查询
    @Test
    public void queryBlogChoose(){
        HashMap map = new HashMap();
//        map.put("title","%如此简单%");
//        map.put("author","狂神说");
        map.put("views","5000");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

使用set元素查询

接口

//    动态sql修改数据库元素
    int updateBlog(Map map);

xml

<!--    动态sql修改数据库元素    set-->
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author},
            </if>
            <if test="views!=null">
                views=#{views}
            </if>
        </set>
        where id = #{id}
    </update>

test

//    update
//动态SQL查询
    @Test
    public void updateBlog(){
        HashMap map = new HashMap();
        map.put("id","58777472fdf54e6db0d28a7c51eaae49");
        map.put("title","mybatis如此简单");
    //        map.put("author","狂神说");
        map.put("views","5000");
        mapper.updateBlog(map);
    }

13.缓存

简介

1、什么是缓存 [ Cache ]?

  • 存在内存中的临时数据。
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2、为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率。

3、什么样的数据能使用缓存?

  • 经常查询并且不经常改变的数据。

Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试

1、在mybatis中加入日志,方便测试结果

2、编写接口方法

//根据id查询用户
User queryUserById(@Param("id") int id);

3、接口对应的Mapper文件

<select id="queryUserById" resultType="user">
  select * from user where id = #{id}
</select>

4、测试

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}

5、结果分析

在这里插入图片描述

一级缓存失效的四种情况

一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

1、sqlSession不同

public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
   session2.close();
}

观察结果:发现发送了两条SQL语句!

结论:每个sqlSession中的缓存相互独立

2、sqlSession相同,查询条件不同

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(2);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}

观察结果:发现发送了两条SQL语句!很正常的理解

结论:当前缓存中,不存在这个数据

3、sqlSession相同,两次查询之间执行了增删改操作!

增加方法

//修改用户
int updateUser(Map map);

编写SQL

<update id="updateUser" parameterType="map">
  update user set name = #{name} where id = #{id}
</update>

测试

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   HashMap map = new HashMap();
   map.put("name","kuangshen");
   map.put("id",4);
   mapper.updateUser(map);

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

观察结果:查询在中间执行了增删改操作后,重新执行了

结论:因为增删改操作可能会对当前数据产生影响

4、sqlSession相同,手动清除一级缓存

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   session.clearCache();//手动清除缓存

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

一级缓存就是一个map

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

使用步骤

1、开启全局缓存 【mybatis-config.xml】

<setting name="cacheEnabled" value="true"/>

2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】

<cache/>

官方示例=====>查看官方文档
<cache
 eviction="FIFO"
 flushInterval="60000"
 size="512"
 readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

3、代码测试

  • 所有的实体类先实现序列化接口
  • 测试代码
@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();

   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   session.close();

   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session2.close();
}

结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

缓存原理图

在这里插入图片描述

EhCache

在这里插入图片描述

第三方缓存实现–EhCache: 查看百度百科

Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

要在应用程序中使用Ehcache,需要引入依赖的jar包

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
   <groupId>org.mybatis.caches</groupId>
   <artifactId>mybatis-ehcache</artifactId>
   <version>1.1.0</version>
</dependency>

在mapper.xml中使用对应的缓存即可

<mapper namespace = “org.acme.FooMapper” >
   <cache type = “org.mybatis.caches.ehcache.EhcacheCache” />
</mapper>

编写ehcache.xml文件,如果在加载时未找到/ehcache.xml资源或出现问题,则将使用默认配置。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false">
   <!--
      diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
      user.home – 用户主目录
      user.dir – 用户当前工作目录
      java.io.tmpdir – 默认临时文件路径
    -->
   <diskStore path="./tmpdir/Tmp_EhCache"/>
   
   <defaultCache
           eternal="false"
           maxElementsInMemory="10000"
           overflowToDisk="false"
           diskPersistent="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="259200"
           memoryStoreEvictionPolicy="LRU"/>

   <cache
           name="cloud_user"
           eternal="false"
           maxElementsInMemory="5000"
           overflowToDisk="false"
           diskPersistent="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="1800"
           memoryStoreEvictionPolicy="LRU"/>
   <!--
      defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
    -->
   <!--
     name:缓存名称。
     maxElementsInMemory:缓存最大数目
     maxElementsOnDisk:硬盘最大缓存个数。
     eternal:对象是否永久有效,一但设置了,timeout将不起作用。
     overflowToDisk:是否保存到磁盘,当系统当机时
     timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
     timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
     diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
     diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
     diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
     memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
     clearOnFlush:内存数量最大时是否清除。
     memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
     FIFO,first in first out,这个是大家最熟的,先进先出。
     LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
     LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
  -->

</ehcache>

xsi:noNamespaceSchemaLocation=“http://ehcache.org/ehcache.xsd”
updateCheck=“false”>

```

合理的使用缓存,可以让我们程序的性能大大提升!

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值