MyBatis

MyBatis

MyBatis

环境:

  • JDK1.8
  • Mysql.5.7
  • maven
  • IDEA

所需知识点:

  • JDBC
  • Mysql
  • java基础
  • Maven
  • Junit

SSM框架:配置文件,最好的方式,看官网,(SprintMVC,SprintBoot,MyBatis)

ORM 对象关系映射 (Object Relational Mapping):将零散的数据封装成一个对象,

1.简介

1.1什么是MyBatis

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5F91zgkX-1656896670001)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220416000534296.png)]

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
  • MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis。2013年11月迁移到Github

如何获取MyBatis

  • Maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.8</version>
</dependency>
  • Github: https://github.com/mybatis/mybatis-3/releases
  • 中文文档:https://mybatis.net.cn/

1.2 持久层

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电及失
  • 保存数据的方式:数据库(jdbc),io文件持久化(浪费资源)

为什么需要持久化

  • 我们希望可以将一些有意义的数据记录下来不会丢失
  • 内存的成本太高

1.3 持久层

Dao层,Service层,Controller层…

  • 完成持久化工作的代码块
  • 层界限十分明显

1.4 为什么需要MyBatis

  • 帮助程序将数据存入数据库中
  • 方便,容易上手
  • 传统的JDBC代码太过于繁琐,简化,框架,自动化

优点:

  • 简单易学
  • 灵活
  • sql和代码的分离,提高了可维护性
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql

最重要的一点:使用的人多!

Spring SpringMVC SpringBoot


2.第一个MyBatis程序

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

2.1 搭建环境

搭建数据库

create database `MyBatis`

use `Mybatis`

create table `user`(
  `id` int comment '主键',
  `name` varchar(50) default null,
  `pwd` varchar(30) default null 
)engine=innodb default charset=utf8

insert into `user`(`id`,`name`,`pwd`)values
(1,'潘表','123456'),
(1,'张三','123321'),
(1,'李四','123654')

新建项目

  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven
  4. 配置pom.xml文件
<!--父工程-->
    <groupId>org.example</groupId>
    <artifactId>Mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.19</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.2 创建一个模块

  • 编写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核心配置文件-->
<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?useSSL=true&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

</configuration>
  • 编写mybatis工具类
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        //获取sqlSessionFactory
        String resource = "org/mybatis/example/mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

2.3 编写代码

  • 实体类
public class User {
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  • Dao接口
public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类由原来的UserDaoImpl转变为一个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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.project.dao.UserDao">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.project.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4 测试

注意点:

MapperRegistry是什么?

核心配置文件中注册 mappers

  • junit测试
public class UserDaoTest {
    @Test
    public void test(){
        SqlSession sqlSession= null;
        try{
            //第一步:获取sqlSession对象
            sqlSession = MybatisUtils.getSqlSession();
            //方式一:执行SQL
            UserDao mapper = sqlSession.getMapper(UserDao.class);
//        List<User> userList = mapper.getUserList();

            //方式二:(了解即可,不推荐使用)
            List<User> userList = sqlSession.selectList("com.project.dao.UserDao.getUserList");


            for (User user : userList) {
                System.out.println(user);
            }
        }finally {
            //关闭SqlSession
            sqlSession.close();
        }
    }
}

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

    <resource>
      <directory>src/main/resources</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>

可能会遇到的问题:

  1. 配置文件没有注册
  2. 绑定接口错误
  3. 方法名不对
  4. 返回类型不对
  5. 资源过滤问题,导致xml为引入

3.CRUD

3.1 namespace

namespace中的包名要和Dao/mapper接口的包名一致!

3.2 select

查询语句:

  • id:就是对应namespace中的方法名
  • resultTyee:sql语句执行的返回值
  • paramterType:参数类型

1.编写接口

//根据ID查询用户
User getUserById(int id);

2.编写对应的mapper中的sql语句

<!--根据用户id查询出用户-->
<select id="getUserById" resultType="com.project.pojo.User" parameterType="int">
  select * from mybatis.user where id = #{id}
</select>

3.测试

@Test
    public void test(){
        SqlSession sqlSession= null;
        try{
            //第一步:获取sqlSession对象
            sqlSession = MybatisUtils.getSqlSession();
            //方式一:执行SQL
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        List<User> userList = mapper.getUserList();

            //方式二:(了解即可,不推荐使用)
            List<User> userList = sqlSession.selectList("com.project.dao.UserMapper.getUserList");

            for (User user : userList) {
                System.out.println(user);
            }
        }finally {
            //关闭SqlSession
            sqlSession.close();
        }
    }

3.3 Insert

配置:

<!--添加一个用户-->
    <insert id="addUser" parameterType="com.project.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>

接口:

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

测试:

@Test
    //注意:增删改需要使用commit提交事务
    public void Test03(){
        //新增一个用户
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int insert = mapper.addUser(new User(4, "王五", "112233"));
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

3.4 update

配置:

<!--修改一个用户-->
    <update id="updateUser" parameterType="com.project.pojo.User">
        update mybatis.user
        set  name=#{name},pwd=#{pwd}
        where id = #{id};
    </update>

接口:

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

测试:

@Test
    public void Test04(){
        //根据id修改用户
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int update = mapper.updateUser(new User(4, "王五", "123333"));
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

3.5 delete

配置:

<!--删除一个用户-->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>

接口:

//删除一个用户
    int deleteUser(int id);

测试:

@Test
    public void Test05(){
        //根据id删除一个用户
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int delete = mapper.deleteUser(4);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

注意点:增删改需要提交事务

错误注意点

  • resource绑定mapper,需要使用路径
  • 程序配置文件必须符合规范!
  • NullPointerException,没有注册到资源
  • 输出的xml文件中存在中文乱码问题
  • maven资源没有导出(资源过滤问题)

3.6 Map集合作为参数

在项目中使用频率较高

我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用map优化

配置:

<!--使用mapper集合添加用户-->
    <insert id="addUserByMap" parameterType="map">
        insert into mybatis.user (id,name,pwd) values(#{userid},#{username},#{password})
    </insert>

接口:

//使用map集合添加一个用户
    int addUserByMap(HashMap<String,Object> mapper);

测试:

@Test
    public void Test06(){
        //使用map接口中的键值对作为对象的属性,以此执行insert命令
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid", 5);
        map.put("username", "娄本伟");
        map.put("password", "332211");

        int i = mapper.addUserByMap(map);
        System.out.println(i);
        sqlSession.commit();

        sqlSession.close();
    }
  • Map传递参数,直接在sql中取出key即可!
  • 对象传递参数,直接在sql中取出的属性即可
  • 只有一个基本类型参数的情况下,可以直接在sql中取到
  • 多个参数用Map,或者注解

3.7 模糊查询

配置:

<!--模糊查询-->
    <select id="getUserByName" resultType="com.project.pojo.User">
        select * from mybatis.user where name like #{value}
    </select>

1.java代码执行的时候,传递通配符% %

select * from mybatis.user where name like #{value}

2.在sql拼接中使用通配符

select * from mybatis.user where name like "%"#{value}"%"

接口:

//模糊查询根据名字查询
    List<User> getUserByName(String value);

测试:

@Test
    public void Test07(){
        //根据名字使用模糊查询
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> ls = mapper.getUserByName("%娄%");
        for (User l : ls) {
            System.out.println(l);
        }
        sqlSession.close();
    }

4. 配置分析

1.核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

2.环境配置(environments)

MyBatis 可以配置成适应多种环境

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZuQEyp8p-1656896670006)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420214740443.png)]

xml的标签有放置顺序

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

<!--环境-->
    <environments default="test">
        <!--环境具体配置-->
      <!--环境1-->
        <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=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

      <!--环境2-->
        <environment id="test">
            <transactionManager type="JDBC"/>
            <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默认的事务管理器就是 JDBC,连接池:POOLED

3.属性(properties)

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

这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过properties元素的子元素来传递。[db.properties]

编写一个配置文件

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/MyBatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

在核心配置文件中映入

<!--引入外部配置文件-->
   	 <properties resource="db.properties" />

			<environment id="test">
            <transactionManager type="JDBC"/>
            <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>
  • 可以直接引入外部文件
  • 可以在其中增加一些配置属性
  • 如果两个文件有同一个字段,优先使用外部配置文件!

4.类型别名(typeAliases)

  • 类型别名是为 Java 类型设置一个短的名字
  • 存在的意义仅在于用用来减少类完全限定名的冗余
<!--别名设置-->
    <typeAliases>
        <typeAlias type="com.project.pojo.User" alias="user"/>
    </typeAliases>

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

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

<!--别名设置(包下匹配Bean)-->
        <package name="com.project.pojo"/>

在实体类比较少的时候,使用第一种方法

如果实体类十分多,建议使用第二种

第一种可以DIY别名,第二种则不行,如果非要改,需要在实体类上增加注解

@Alias("opgg")
public class User {

5.设置(settings)

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

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
aggressiveLazyLoading开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods)。true | falsefalse (在 3.4.1 及之前的版本中默认为 true)
multipleResultSetsEnabled是否允许单个语句返回多结果集(需要数据库驱动支持)。true | falsetrue
useColumnLabel使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。true | falsetrue
useGeneratedKeys允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。true | falseFalse
autoMappingBehavior指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。NONE, PARTIAL, FULLPARTIAL
autoMappingUnknownColumnBehavior指定发现自动映射目标未知列(或未知属性类型)的行为。NONE: 不做任何反应WARNING: 输出警告日志('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARNFAILING: 映射失败 (抛出 SqlSessionException)NONE, WARNING, FAILINGNONE
defaultExecutorType配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。SIMPLE REUSE BATCHSIMPLE
defaultStatementTimeout设置超时时间,它决定数据库驱动等待数据库响应的秒数。任意正整数未设置 (null)
defaultFetchSize为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。任意正整数未设置 (null)
defaultResultSetType指定语句默认的滚动策略。(新增于 3.5.2)FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT(等同于未设置)未设置 (null)
safeRowBoundsEnabled是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。true | falseFalse
safeResultHandlerEnabled是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。true | falseTrue
mapUnderscoreToCamelCase是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。true | falseFalse
localCacheScopeMyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。SESSION | STATEMENTSESSION
jdbcTypeForNull当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。OTHER
lazyLoadTriggerMethods指定对象的哪些方法触发一次延迟加载。用逗号分隔的方法列表。equals,clone,hashCode,toString
defaultScriptingLanguage指定动态 SQL 生成使用的默认脚本语言。一个类型别名或全限定类名。org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5)一个类型别名或全限定类名。org.apache.ibatis.type.EnumTypeHandler
callSettersOnNulls指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。true | falsefalse
returnInstanceForEmptyRow当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2)true | falsefalse
logPrefix指定 MyBatis 增加到日志名称的前缀。任何字符串未设置
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置
proxyFactory指定 Mybatis 创建可延迟加载对象所用到的代理工具。CGLIB | JAVASSISTJAVASSIST (MyBatis 3.3 以上)
vfsImpl指定 VFS 的实现自定义 VFS 的实现的类全限定名,以逗号分隔。未设置
useActualParamName允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1)true | falsetrue
configurationFactory指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3)一个类型别名或完全限定类名。未设置
<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>

6.其他配置

7.映射器(mappers)

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

方式一:【推荐使用!没有任何限制】

<mappers>
  			<!--使用相对于类路径的资源引用-->
        <mapper resource="com/project/dao/UserMapper.xml"/>
</mappers>

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

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

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

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

注意点:

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

8.生命周期和作用域

声明周期,作用域,是至关重要的,因为错误的使用会导致严重的并发问题

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KoPBVVMx-1656896670007)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420225837498.png)]

SqlSessionFactoryBuilder

  • 一旦创建了 sqlSessionFactory 就没有存在的必要了
  • 局部变量

SqlSessionFactory

  • 说白了就是可以想象为:数据库连接池
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃或重新创建一个实例
  • 因此 SqlSessionFactory 的最佳作用域就是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wday8xuk-1656896670008)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420230705350.png)]

这里面的每一个Mapper都是为了执行一个业务~!

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

1.问题

  • 如果我们的实体类与数据库中的字段名不一致将会出现一些问题

实体类

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1zR6qayh-1656896670009)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233831796.png)]

数据库字段

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rQBwSvnB-1656896670009)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233903240.png)]

当不一致时出现的结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KJ2KHZY3-1656896670010)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220420233751245.png)]

我们发现不一致的字段返回值为空

2. resultMap

结果集映射

id name pwd
id name password
 <!--结果集映射-->
<resultMap id="getUserById" type="user">
  <!--column指的是数据库中的字段,property指的是实体类中的属性-->
  <!--只需要映射字段名与属性名不一样的即可-->
  <!--<result column="id" property="id"/>-->
  <!--<result column="name" property="name"/>-->
  <result column="pwd" property="password"/>
</resultMap>

<!--select查询语句-->
<select id="getUserById" resultType="user" resultMap="getUserById" parameterType="int">
  select * from mybatis.user where id = #{id}
</select>
  • resultMap 元素是MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述他们的关系就好了
  • ResultMap 最优秀的地方在于,虽然你已经对他相当了解了,但你根本就需要显示的用到他们

6.日志

6.1日志工厂

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

曾经:sout,debug

现在:日志工厂!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mS3VDeWi-1656896670011)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220421165137276.png)]

  • SJF4J
  • LOG4J
  • LOG4J2
  • JDK_LOGGING
  • COMMOSN_LOGGING
  • STDOUT_LOGGING
  • NO_LOGGING
<settings>
        <!--默认实现日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BBfBWQfZ-1656896670011)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220421171914620.png)]

6.2 LOG4J

什么是LOG4J?

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

1.先导入Log4j的包

<!--LOG4J-->
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.12</version>
</dependency>

2.配置mybatis-config.xml

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

3.Log4j配置文件

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/kuang.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

简单使用

  1. 在要使用Log4j的类中,导入包 import org.appche.log4j.Logger
  2. 日志对象,参数为当前类的class
Logger logger = Logger.getLogger(UserDaoTest.class);
  1. 日志级别
logger.info("info:进入了testLog4j");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");

7.分页

7.1 Limit实现分页

  • 接口
//实现分页查询
List getUserByLimit(Map map);
  • 配置
<!--实现分页查询-->
<select id="getUserByLimit" resultType="user" resultMap="getUserById" parameterType="map">
  select * from mybatis.user limit #{startPage},#{pageSize}
</select>
  • 测试
@Test
public void Test01(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  HashMap<String, Integer> map = new HashMap<>();
  map.put("startPage", 0);
  map.put("pageSize",3);
  List list =  mapper.getUserByLimit(map);
  for (Object o : list) {
    System.out.println(o);
  }
  sqlSession.close();
}

7.2 RowBounds实现分页

  • 接口
//实现分页查询(RowBounds)
List getUserByRowBounds();
  • 配置
<!--实现分页查询-->
<select id="getUserByRowBounds" resultType="user" resultMap="getUserById">
  select * from mybatis.user
</select>
  • 测试
@Test
public void Test02(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  RowBounds rowBounds = new RowBounds(1,2);
  List<Object> objects = sqlSession.selectList("com.project.dao.UserMapper.getUserByRowBounds",null,rowBounds);
  for (Object object : objects) {
    System.out.println(object);
  }
  sqlSession.close();
}

8.使用注解开发

8.1 面向接口编程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6EGkWx59-1656896670012)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220424215920535.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-98ALnV8u-1656896670013)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220424215939852.png)]

8.2 使用注解开发

接口

 @Select("select * from user")
public ArrayList<User> getUserByList();

配置

<mappers>
  <mapper class="com.project.dao.UserMapper"/>
</mappers>

测试

@Test
public void test(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  List list = mapper.getUserByList();
  for (Object o : list) {
    System.out.println(o);
  }
  sqlSession.close();
}

本质:反射机制实现

底层:动态代理!

8.3 MyBatis执行流程

8.4 CRUD

关于@Param() 注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议加上
  • 我们在SQL中引用的就是我们这里的@Param() 中设定的属性名
8.4.1 select

接口

@Select("select * from user where id = #{id}")
User getUserById(@Param("id")int id);

测试

@Test
public void getUserByIdTest(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  User userById = mapper.getUserById(1);
  System.out.println(userById);
  sqlSession.close();
}
8.4.2 insert

接口

@Insert("insert into user (`id`,`name`,`pwd`) values(#{id},#{name},#{password})")
int addUser(User user);

测试

@Test
public void addUserTest(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  int hello = mapper.addUser(new User(7, "hello", "123321"));
  sqlSession.close();
}
8.4.3 update

接口

@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updUser(User user);

测试

@Test
public void updUserTest(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  int hello = mapper.updUser(new User(7, "jordan", "123321"));
  sqlSession.close();
}
8.4.4 delete

接口

@Delete("delete from user where id=#{id}")
int delUser(@Param("id") int id);

测试

@Test
public void delUserTest(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  mapper.delUser(7);
  sqlSession.close();
}

9.Lombok

9.1 Maven导入

<!--Lombok-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.22</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>RELEASE</version>
  <scope>compile</scope>
</dependency>

使用

@Data
public class User {
    private int id;
    private String name;
    private String password;
}

优点:

使用Lombok插件可以简化getter和setter的代码,以及构造参数,我们可以使用data注解来创建这些代码

缺点:

破坏了源码的结构,破坏了java语言的规范与统一性

10.多对一处理

  • 一对多和多对一的关系是一种较为复杂的关系
  • 其中在于站在谁的方位上看
  • 如老师,学生
  • 学生只能有一个老师(多对一)
  • 老师有很多学生(一对多)
CREATE DATABASE `MyBatis`

USE `Mybatis`

CREATE TABLE `student`
(
	`id` INT COMMENT '学号',
	`name` VARCHAR(30) NOT NULL COMMENT '姓名',
	`tid` INT COMMENT '教室编号',
	PRIMARY KEY (`id`),
	FOREIGN KEY(`tid`) REFERENCES `teacher`(`id`)
)ENGINE = INNODB DEFAULT CHARSET=utf8

CREATE TABLE `teacher`
(
	`id` INT COMMENT '教室编号',
	`name` VARCHAR(30) NOT NULL COMMENT '教师姓名',
	PRIMARY KEY (`id`)
)ENGINE = INNODB DEFAULT CHARSET=utf8

INSERT `student` VALUES
(1,'张三',1),
(2,'李四',1),
(3,'王五',1),
(4,'赵六',1),
(5,'giao哥',1)

INSERT `teacher` VALUES
(1,'卢本伟')

测试环境搭建

  1. 导入lombok
  2. 新建实体类 Teacher,Student
  3. 建议Mapper接口
  4. 建立Mapper.XML文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!
  6. 测试查询是否能够成功!

按照查询嵌套处理

接口

List getStudents();

配置

 <!--
    思路:
        1.查询所有的学生信息
        2.根据查询处理的学生的tid,寻找对应的老师!:子查询
    -->
<select id="getStudents" resultMap="studentTeacher">
  select * from student
</select>
<resultMap id="studentTeacher" type="student">
  <result property="id" column="id"/>
  <result property="name" column="name"/>
  <!--复杂的属性,我们需要单独处理,对象:association 集合:collection-->
  <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
  select * from teacher where id = #{id}
</select>

测试

@Test
public void test02(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
  List students = mapper.getStudents();
  for (Object student : students) {
    System.out.println(student);
  }
  sqlSession.close();
}

按照结果嵌套处理

配置:

<select id="getStudents2" resultMap="studentsTeacher2">
  select s.id sid,s.name sname,t.name tname
  from student s,teacher t
  where s.tid = t.id
</select>
<resultMap id="studentsTeacher2" type="student">
  <result property="id" column="sid"/>
  <result property="name" column="sname"/>
  <association property="teacher" javaType="teacher">
    <result property="name"  column="tname"/>
  </association>
</resultMap>

回顾Mysql 多对一查询方式:

  • 子查询
  • 联表查询

11.一对多处理

一对多的处理方式与多对一类似

环境搭建

实体类

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

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

按照结果集嵌套处理

<select id="getTeacherByStudent" resultMap="TeacherStudent">
  select s.id sid,s.name sname,t.id tid,t.name tname
  from student s,teacher t
  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 property="id" column="sid"/>
    <result property="name" column="sname"/>
    <result property="tid" column="tid"/>
  </collection>
</resultMap>

按照查询嵌套处理

<select id="getTeacherByStudent2" resultMap="TeacherStudent2">
  select * from teacher where id = #{tid}
</select>

<resultMap id="TeacherStudent2" type="teacher">
  <collection property="students" javaType="ArrayList" ofType="student" select="getStudentByTeacherId"  column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="student">
  select * from student where tid = #{tid}
</select>

回顾Mysql 多对一查询方式:

  • 子查询
  • 联表查询

小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. JavaType & ofType
    1. JavaType:用来指定实体类中属性的类型
    2. ofType:用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志【LOG4J】

12.动态 SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句

所谓的动态SQL,本质还是SQL语句,只要我们可以在SQL层面,去执行一个逻辑代码

利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解,MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素即可 MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其他大部分元素


环境搭建

CREATE DATABASE `MyBatis`

USE `Mybatis`

CREATE TABLE `blog`(
  `id` VARCHAR(50) NOT NULL COMMENT '博客id',
  `title` VARCHAR(100) NOT NULL COMMENT '博客标题',
  `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
  `create_time` DATETIME NOT NULL COMMENT '创建时间',
  `views` INT(30) NOT NULL COMMENT '浏览器'
)ENGINE = INNODB DEFAULT CHARSET=utf8

IF

这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。

如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。

配置sql

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

接口

//动态Sql
List<Blog> queryBolgIF(Map map);

测试

@Test
public void test02(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
  HashMap map = new HashMap();
  map.put("title", "Java");
  List<Blog> blogs = mapper.queryBolgIF(map);
  for (Blog blog : blogs) {
    System.out.println(blog);
  }
  sqlSession.close();
} 

choose (when,otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。

<select id="queryBolgChoose" parameterType="map" resultType="Blog">
  select * from blog
  <where>
    <choose>
      <when test="title != null">
        title = #{titie}
      </when>
      <when test="author != null">
        and author = #{author}
      </when>
      <otherwise>
        and views = #{views}
      </otherwise>
    </choose>
  </where>
</select>

测试类

@Test
public void test03(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
  HashMap map = new HashMap();
  //        map.put("title", "Java");
  //        map.put("author", "狂神说");
  map.put("views", "9999");
  List<Blog> blogs = mapper.queryBolgChoose(map);
  for (Blog blog : blogs) {
    System.out.println(blog);
  }
  sqlSession.close();
}

trim(where,set)

where

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

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

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)

<update id="updBlogSet" 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
public void test04(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
  HashMap map = new HashMap();
  map.put("title", "Java2");
  map.put("author", "狂神说2");
  map.put("views", "999");
  map.put("id", "6587f430c56a4a08995eb453b33c2c4e");
  int i = mapper.updBlogSet(map);
  sqlSession.close();
}
trim

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  
</trim>

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

<trim prefix="SET" suffixOverrides=",">
  
</trim>

et 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

注意,我们覆盖了后缀值设置,并且自定义了前缀值。

SQL片段

有的时候,我们可能会将一些功能的部份抽取出来,方便复用

1.使用SQL标签抽取公共部份

<!--定义sql片段-->
<sql id="if-title-author">
  <if test="title != null">
    and title = #{title}
  </if>
  <if test="author != null">
    and author = #{author}
  </if>
</sql>

2.在需要使用的地方使用include标签引用即可

<select id="queryBlogIF_Sql" parameterType="map" resultType="Blog">
  select * from blog
  <where>
    <include refid="if-title-author"/>
  </where>
</select>

foreache

<select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="(" separator="or" close=")">
               id = #{id}
            </foreach>
        </where>
</select>
  • collection:目标集合
  • item:遍历后的对象
  • open:前缀
  • close:后缀
  • separator:分隔符(or,and)
@Test
public void test06(){
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
  HashMap map = new HashMap();
  ArrayList list = new ArrayList();
  list.add(1);
  list.add(2);
  list.add(3);
  //如果list为空则不进入foreach循环,执行select * from blog 语句
  map.put("ids",list);
  List<Blog> arr = mapper.queryBlogForeach(map);
  for (Blog blog : arr) {
    System.out.println(blog);
  }
  sqlSession.close();
}

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

面试高频

  • Mysql引擎
  • innoDB底层原理
  • 索引
  • 索引优化

13.缓存

13.1 简介

  1. 什么是缓存 [ Cache ]?
    • 存在内存中的临时数据
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就用不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发性能的问题
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率
  3. 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据【推荐使用缓存】

13.2 Mybatis缓存

  • MyBatis包含了一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大提升查询效率
  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启,(SqlSession级别的缓存,也成为本地缓存)
    • 二级缓存需要手动开启和配置,他是给予namespace级别的缓存
    • 为了提高拓展性,MyBatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存

13.3 一级缓存

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AgL7hJWL-1656896670014)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220501172357381.png)]一级缓存是默认开启的,只存在于Sqlsession中

缓存失效的情况:

  1. 查询不同的东西
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
  3. 查询不同的Mapper.xml
  4. 手动清理缓存 【sqlSession.clearCache();//手动清理缓存】

13.4 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中

步骤:

  1. 开启全局缓存
<!--显示开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存的Mapper中开启
<cache/>

也可以开启策略

这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

<cache eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cElgyGLr-1656896670014)(C:\Users\潘文锋\AppData\Roaming\Typora\typora-user-images\image-20220501181213868.png)]

  1. 测试
@Test
public void test2(){
  SqlSession sqlSession1 = MybatisUtils.getSqlSession();
  SqlSession sqlSession2 = MybatisUtils.getSqlSession();

  UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
  UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);

  User userById = mapper1.getUserById(1);

  sqlSession1.close();
  User userById1 = mapper2.getUserById(1);
  sqlSession2.close();
}

注意:

​ 如果cache标签没有开启策略需要将对象序列化(实现Serializable接口)

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交或者关闭的时候,才会提交到二级缓存中

13.5 缓存原理

13.6 自定义缓存

ehcache

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值