Mybatis学习笔记(狂神说)

1、简介

狂神说https://space.bilibili.com/95256449

1.1 什么是Mybatis

在这里插入图片描述

  • MyBatis 是一款优秀的持久层框架;
  • 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。如何获得

如何获得Mybatis?

1.2持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

  • 内存:断电即失

  • 数据库(Jdbc),io文件持久化。

为什么要持久化?

  • 有一些对象,不能让他丢掉

  • 内存太贵

1.3 持久层

Dao层、Service层、Controller层
完成持久化工作的代码块层界限十分明显

1.4 为什么需要MyBatis

  • 帮助程序员将数据存入到数据库中

  • 方便

  • 传统的JDBC代码太复杂了,简化,框架,自动化

  • 不用MyBatis也可以,技术没有高低之分

  • 优点:

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

2、第一个Mybatis程序

思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试

2.1 搭建环境

新建项目

  1. 创建一个普通的maven项目

  2. 删除src目录 (就可以把此工程当做父工程了,然后创建子工程)

  3. 导入maven依赖

        <dependencies>
    
            <!--连接mysql数据库依赖-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.1</version>
                <scope>test</scope>
            </dependency>
    
        </dependencies>
    

2.2 创建一个模块

  • 编写mybatis的核心配置文件

    • ​ 注意mysql5.7是 com.mysql.cj.jdbc.Driver和8.0 是com.mysql.cj.jdbc.Driver版本
    <?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.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
    
  • 编写mybatis工具类

    //sqlSessionFactory --> sqlSession
    public class MybatisUtils {
    
        static SqlSessionFactory sqlSessionFactory = null;
    
        static {
            try {
                //使用Mybatis第一步 :获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    
    

2.3 编写代码

  • 实体类

  • Dao接口

    public interface UserDao {
        public List<User> getUserList();
    }
    
  • 接口实现类 (由原来的UserDaoImpl转变为一个Mapper配置文件)

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--namespace=绑定一个指定的Dao/Mapper接口-->
    <mapper namespace="com.kuang.dao.UserDao">
        <select id="getUserList" resultType="com.th.pojo.User">
        select * from USER
      </select>
    </mapper>
    
    

    测试代码

        @Test
        public void test(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);
    
            }
            
        }
    

    注意点(错误):

    org.apache.ibatis.binding.BindingException: Type interface com.th.Dao.UserDao is not known to the MapperRegistry.

    MapperRegistry是什么?

    ​ 核心配置文件中注册mappers

    <?xml version="1.0" encoding="UTF8" ?>
    <!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;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <mapper resource="com/th/Dao/UserMapper.xml"></mapper>
        </mappers>
    
    </configuration>
    
    

    在两个pom.xml中加入(应该在父项目的pom加就好了)

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

    不用怀疑没有任何问题

    可能会遇到的问题:

    1. 配置文件没有注册
    2. 绑定接口错误
    3. 方法名不对
    4. 返回类型不对
    5. Maven导出资源问题

步骤

  1. 导入包
  2. 配置数据库
  3. 建造工具类

2.4了解

SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。 下面的示例就是一个确保 SqlSession 关闭的标准模式

3. 增删改查

1. namespace

namespace中的包名要和接口一致

2. select

  • id:就是对应的namespace的方法名
  • resultType:sql语句的返回值!
  • parameterType: 参数类型!
  1. 编写接口
  2. 编写对应的mapper中的对应语句
  3. 测试

UserMapper

package com.th.Dao;

import com.th.pojo.User;

import java.util.List;

/**
 * @Author 天红
 * @Date 2021/8/5 21:27
 * @Version 1.0
 */
public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

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

    //    插入用户
    int addUser(User user);

    //    修改用户
    int UpdateUser(User user);

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

}

UserMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace=绑定一个指定的Dao/Mapper接口-->
<mapper namespace="com.th.Dao.UserMapper">
    <select id="getUserList" resultType="com.th.pojo.User">
        select *from mybatis.user
    </select>

    <select id="getUserById" resultType="com.th.pojo.User" parameterType="int">
        select * from user where id=#{id}
    </select>

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

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

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

测试

package com.th;

import com.th.Dao.UserMapper;
import com.th.pojo.User;
import com.th.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @Author 天红
 * @Date 2021/8/5 21:35
 * @Version 1.0
 */
public class Test_User {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            System.out.println(user);

        }
    }

    @Test
    public void test1(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User userById = userMapper.getUserById(2);
        System.out.println(userById);
        

        sqlSession.commit();    //提交事务
        sqlSession.close();
    }

    @Test
    public  void test2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int num = userMapper.addUser(new User(5, "摩尔", "123"));
        if (num>0){
            System.out.println("success=========");
        }


        sqlSession.commit();
        sqlSession.close();

    }



    @Test
    public  void test3(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.UpdateUser(new User(1,"上帝","333"));

        sqlSession.commit();
        sqlSession.close();

    }


    @Test
    public  void test4(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUser(1);

        sqlSession.commit();
        sqlSession.close();

    }
}

3. Map

假如我们的实体类属性过多,用map,传递map的key

int addUser2(Map<String, Object> map);
<insert id="addUser2" parameterType="map">
    insert into user (id, name, pwd) values (#{id1}, #{name1}, #{pwd1});
</insert>
        

这个键可以自己看着定义

@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id1",11);
    map.put("name1","部分");
    map.put("pwd1","12345");
    mapper.addUser2(map);

    //提交事务
    sqlSession.commit();
    sqlSession.close();
}

4.模糊查询

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

(传递通配符%两种都可以)

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

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

看下面可以逆推出接口了

<select id="getUserLike" resultType="com.th.pogo.User">
    select * from user where name like #{value}
</select>
@Test
public void getUserLike(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> list = mapper.getUserLike("%他%");

    for(User user : list){
        System.out.println(user);
    }

    sqlSession.close();
}

4、配置解析(mybatis-config.xml)

1. 核心配置文件mybatis-config.xml

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

2. 环境配置(environments)

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

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

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

3. 属性

我们可以通过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&serverTimezone=UTC
username=root
password=root

在核心配置文件中引入

mybatis-config.xml (同时有的话,优先走外面properties)

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <!--引用外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>

    <environments default="development">
        <environment id="development">
            <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>

    <mappers>
        <mapper resource="com/th/Dao/UserMapper.xml"></mapper>
    </mappers>

</configuration>

4. 类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。

<typeAliases>    <typeAlias type="com.th.pojo.User" alias="User"></typeAlias> </typeAliases>

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

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

在实体类,比较少的时候使用第一种,实体类多使用第二种。

第一种可以自定义,第二则不行,但是 若有注解,则别名为其注解值 。

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

5. 设置

设置名 描述 有效值 默认值
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 true | false false
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

6. 其他(看一眼就好)

7. 映射器

方式一: [推荐使用]

<mappers>
    <mapper resource="com/th/dao/UserMapper.xml"/>
</mappers>

方式二:

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

接口和它的Mapper必须同名

接口和他的Mapper必须在同一包下

方式三:

<mappers>
    <!--<mapper resource="com/th/dao/UserMapper.xml"/>-->
    <!--<mapper class="com.th.dao.UserMapper" />-->
    <package name="com.th.dao" />
</mappers>
  • 接口和它的Mapper必须同名
  • 接口和他的Mapper必须在同一包下

8.生命周期和作用域

在这里插入图片描述

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

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了 。
  • 局部变量

SqlSessionFactory

  • 就是数据库连接池。
  • 一旦被创建就应该在应用的运行期间一直存在 ,没有任何理由丢弃它或重新创建另一个实例 。 多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession

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

在这里插入图片描述

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

1. 问题

数据库中的字段

在这里插入图片描述

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

在这里插入图片描述

测试出现问题(参考多人的笔记,图片处理浪费时间,出现了中间那句话是把useSSL拼错了,不应该有)
在这里插入图片描述

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

解决方法:

  • 起别名
<select id="getUserById" resultType="com.kuang.pojo.User">
    select id,name,pwd as password from USER where id = #{id}
</select>

2.resultMap

结果集映射

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace=绑定一个指定的Dao/Mapper接口-->
<mapper namespace="com.th.Dao.UserMapper">

<resultMap id="userMap" type="user">
<!--   一样的可以不改 -->
<!--    <id column="id" property="id" ></id>-->
<!--    <result column="name" property="name"></result>-->
    <result column="pwd" property="password"></result>
</resultMap>
    <select id="getUserById" resultMap="userMap">
        select * from user where id=#{id}
    </select>
</mapper>

  • resultMap 元素是 MyBatis 中最重要最强大的元素。

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。

  • 如果这个世界总是这么简单就好了。

6. 日志

1. 日志工厂

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

曾经:sout,debug

现在:日志工厂

logImpl

  • SLF4J
  • LOG4J [掌握]
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING [掌握]
  • NO_LOGGING

具体使用哪一个,在设置中设定

STDOUT_LOGGING 标志日志输出

mybatis-config.xml中

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

2. Log4j

  1. 先导包

    pom.xml下

    <dependencies>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    
  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/rzp.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.sq1.PreparedStatement=DEBUG
    
    
  3. 配置settings为log4j实现

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  4. 测试运行

package com.th;

import com.th.Dao.UserMapper;
import com.th.pojo.User;
import com.th.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;


/**
 * @Author 天红
 * @Date 2021/8/5 21:35
 * @Version 1.0
 */
public class Test_User {
    static Logger logger = Logger.getLogger(Test_User.class);

    @Test
    public void test1() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            logger.info("============================测试着玩");
            User userById = userMapper.getUserById(2);
            logger.info("++++++++++" + userById + "++++++++++++++");
            logger.info("============================他化自在");

            System.out.println(userById);

            //提交事务,默认有。可不写
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close(); //关闭
        }
    }


    @Test
    public void test_log4j() {
        logger.info("info:进入了testlog4j");
        logger.debug("debug:进入了testlog4j");
        logger.error("error:进入了testlog4j");
    }
}

Log4j简单使用

  • 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;

  • 日志对象,参数为当前类的class对象

    Logger logger = Logger.getLogger(UserDaoTest.class);
    
  • 日志级别

    info
    debug
    error

7、分页

思考:为什么分页?

  • 减少数据的处理量

7.1 使用Limit分页

SELECT * from user limit startIndex,pageSize 

使用MyBatis实现分页,核心SQL

接口

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

Mapper.xml

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

测试

    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",1);
        map.put("pageSize",2);
        List<User> list = mapper.getUserByLimit(map);
        for (User user : list) {
            System.out.println(user);
        }
    }

7.2 RowBounds分页(了解下,老了)

不再使用SQL实现分页

  • 接口
//分页2
List<User> getUserByRowBounds();
  • mapper.xml
<!--分页查询2-->
<select id="getUserByRowBounds">
    select * from user limit #{startIndex},#{pageSize}
</select>
  • 测试
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 3);
        //通过Java代码层面实现分页
        List<User> userList = sqlSession.selectList("com.th.dao.UserMapper.getUserByRowBounds", null, rowBounds);
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

7.3 分页插件

img

8、使用注解开发

简单的sql用注解,复杂的用xml

8.1 面向接口开发

三个面向区别

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

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

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

8.2 使用注解开发

  1. 注解在接口上实现

    @Select("select * from user")
    List<User> getUsers();
    
  2. 需要在核心配置文件中绑定接口

<mappers>
    <mapper class="com.th.dao.UserMapper"/>
</mappers>
  1. 测试

    package com.th;
    
    import com.th.dao.UserMapper;
    import com.th.pojo.User;
    import com.th.util.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    
    /**
     * @Author 天红
     * @Date 2021/8/5 21:35
     * @Version 1.0
     */
    public class Test_zj {
        @Test
        public void test() {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getUsers();
            for (User user : users) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    }
    

本质:反射机制实现

底层:动态代理

在这里插入图片描述

MyBatis详细执行流程

  1. Resource获取全局配置文件
  2. 实例化SqlsessionFactoryBuilder
  3. 解析配置文件流XMLCondigBuilder
  4. Configration所有的配置信息
  5. SqlSessionFactory实例化
  6. trasactional事务管理
  7. 创建executor执行器
  8. 创建SqlSession
  9. 实现CRUD
  10. 查看是否执行成功
  11. 提交事务
  12. 关闭

在这里插入图片描述

8.3 注解CURD(复杂的不行)

  • 接口
package com.th.dao;

import com.th.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    //方法存在多个参数,所有的参数必须加@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

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

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

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

}
  • MybatisUtile
package com.th.utils;

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;

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }

}
  • 测试
package com.th.dao;

import com.th.pojo.User;
import com.th.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userDao.getUsers();
            for (User user : userList) {
                System.out.println(user);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void getuserById(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            User user = userDao.getUserById(1);

            System.out.println(user);


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void addUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.addUser(new User(6, "kun","123"));

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void updateUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.updateUser(new User(6, "fang","123"));

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void deleteUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.deleteUser(6);

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }
}

关于@Param( )注解

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

#{} 和 ${}

  • a、#{}是预编译处理,${}是字符串替换。
  • b、Mybatis 在处理#{}时,会将 sql 中的#{}替换为?号,调用 PreparedStatement 的 set 方法来赋值;
  • c、Mybatis 在处理${}时,就是把${}替换成变量的值。
  • d、使用#{}可以有效的防止 SQL 注入,提高系统安全性。

9、Lombok

Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。

使用步骤:

  1. 在IDEA中安装Lombok插件 在项目中导入lombok的jar包
  2. 在项目中导入lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
    <scope>provided</scope>
</dependency>

在程序上加注解

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val

例如

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

10、多对一处理

property 映射到列结果的字段或属性。

column 数据库中的列名,或者是列的别名。

  • 多个学生关联一个老师(多对一)
  • 集合(一对多)

10.1. 测试环境搭建

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

1. 建表

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);
  • 新建实体类

    package com.th.pojo;
    
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
    
    /**
     * @Author 天红
     * @Date 2021/8/7 10:06
     * @Version 1.0
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {
        private int id;
        private String name;
    
        //学生需要关联一个老师
        private Teacher teacher;
    }
    
    
    package com.th.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @Author 天红
     * @Date 2021/8/7 10:07
     * @Version 1.0
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Teacher {
        private int id;
        private String name;
    }
    
    

10.2. 按照查询嵌套处理

select * from student

select * from teacher where id = #{id};

  • 建立Mapper接口

    public interface StudentMapper {
        public List<Student> getStudent();
    }
    
    public interface TeacherMapper {
        @Select("select * from teacher where id = #{tid}")
        Teacher getTeacher(@Param("tid") int id);
    }
    
  • Mapper.xml

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--configuration核心配置文件-->
    <mapper namespace="com.th.dao.StudentMapper">
        <!--
         思路:
            1. 查询所有的学生信息
            2. 根据查询出来的学生的tid寻找特定的老师 (子查询)
        -->
        <select id="getStudent" resultMap="StudentTeacher">
            select * from student
    
        </select>
    
        <resultMap id="StudentTeacher" type="student">
            <result property="id" column="id"></result>
            <result property="name" column="name"/>
            <!--复杂的属性,我们需要单独出来 对象:association 集合:collection-->
            <association property="teacher" column="tid" javaType="teacher" select="getTeacher">
            </association>
        </resultMap>
    
        <select id="getTeacher" resultType="teacher">
            select * from teacher where id = #{id};
        </select>
    
    </mapper>
    
  • 配置文件

    <mappers>
    <!--        <mapper resource="com/th/dao/TeacherMapper.xml"></mapper>-->
            <mapper resource="com/th/dao/StudentMapper.xml"></mapper>
          </mappers>
    
  • 测试

        @Test
        public void test1(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            List<Student> student = mapper.getStudent();
            System.out.println("=====================================");
    
            for (Student student1 : student) {
                System.out.println(student1);
            }
            sqlSession.close();
        }
    

10.3按照结果嵌套处理

同理参考上10.2
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id;

    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t where s.tid=t.id;
    </select>

    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
        <association property="teacher" javaType="teacher">
            <result property="id" column="tid"></result>
            <result property="name" column="tname"></result>
        </association>

    </resultMap>

回顾Mysql多对一查询方式:

  • 子查询 (按照查询嵌套)
  • 联表查询 (按照结果嵌套)

11、一对多处理

一个老师多个学生;

对于老师而言,就是一对多的关系;

1.环境搭建

  • 实体类
@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> studentList;
}
  • 接口
public interface TeacherMapper {
   Teacher getTeacher(@Param("id") int id);
}

2. 按照结果查询

  • TeacherMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.th.dao.TeacherMapper">
    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid, s.name sname, t.name tname, t.id tid
    from student s, teacher t
    where s.tid = t.id and t.id = #{id};
</select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <!--集合中的泛型信息,我们用oftype获取-->
        <collection property="studentList" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
        </collection>
    </resultMap>
    
</mapper>
  • 配置
    <!--    <mappers>-->
    <!--        <mapper class="com.th.dao.TeacherMapper"></mapper>-->
    <!--    </mappers>-->
    <mappers>
        <mapper resource="com/th/dao/TeacherMapper.xml"></mapper>
    </mappers>
  • 测试
    @Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println("=====================================");
        System.out.println(teacher);
        sqlSession.close();
    }

3. 按照查询嵌套处理

同理参考上

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

<resultMap id="TeacherStudent2" type="com.th.pojo.Teacher">
    <collection property="studentList" column="id" javaType="ArrayList"
                ofType="com.th.pojo.Student"
                select="getStudentByTeacherId"></collection>
</resultMap>

<select id="getStudentByTeacherId" resultType="com.th.pojo.Student">
    select * from student where tid = #{id}
</select>

小结

  1. 关联 - association 多对一
  2. 集合 - collection 一对多
  3. javaType & ofType
    1. JavaType用来指定实体中属性类型
    2. ofType映射到list中的类型,泛型中的约束类型

注意点:

  • 保证sql可读性,尽量保证通俗易懂
  • 注意字段问题
  • 如果问题不好排查错误,使用日志

面试高频

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

12、动态SQL

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

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

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

1搭建环境

create table `blog`(
	`id` varchar(80) 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 '浏览量',
    PRIMARY KEY (`id`)
	)ENGINE=InnoDB DEFAULT CHARSET=utf8

创建一个基础工程

  1. 导包

  2. 编写配置文件

        <mappers>
            <mapper resource="com/th/dao/BlogMapper.xml"></mapper>
        </mappers>
    
  3. 编写实体类

    @Data
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    
  4. 编写实体类对应Mapper接口和Mapper.xml文件

    public interface BlogMapper {
        public int addBlog(Blog blog);
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.th.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
            insert into blog(id,title,author,create_time,views)values (#{id},#{title},#{author},#{createTime},#{views});
        </insert>
    </mapper>
    
  5. IDUtiles(随机id的工具类,自己看着写就好

    package com.th.util;
    import java.util.UUID;
    /**
     * @Author 天红
     * @Date 2021/8/7 20:43
     * @Version 1.0
     */
    @SuppressWarnings("all")
    public class IDUtiles {
    
        public static String getId() {
            return UUID.randomUUID().toString().replaceAll("-", "");
        }
    }
    
    • db.properties

      提醒一下自己

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

2.IF

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

测试

    @Test
    public void queryBlogIF() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();

        map.put("author", "魔");
     
        List<Blog> list = blogMapper.queryBlogIF(map);

        for (Blog blog : list) {
            System.out.println(blog);
        }
        sqlSession.commit();
        sqlSession.close();
    }

3. choose、when、otherwise(只选择一个)

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

4. trim、where、set(去除前缀后缀)

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </set>
    where id = #{id}
</update>

trim 可以自定义

SQL片段

有些时候我们有一些公共部分

  1. 使用sql便签抽取公共部分
  2. 在使用的地方使用include标签
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>


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

注意:

  • 最好基于单表
  • sql里不要存在where标签

5. for-each

<!--ids是传的,#{id}是遍历的-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="and ("
                 close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

测试

@Test
public void queryBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();

    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(3);
    map.put("ids",ids);

    List<Blog> list = blogMapper.queryBlogForeach(map);

    for (Blog blog : list) {
        System.out.println(blog);
    }

    sqlSession.close();
  • 先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可

13、缓存

13.1 简介

查询 : 连接数据库,耗资源
一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了

  • 什么是缓存[Cache]?

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

    1. 减少和数据库的交互次数,减少系统开销,提高系统效率
  • 什么样的数据可以使用缓存?

  1. 经常查询并且不经常改变的数据 【可以使用缓存】

13.2 MyBatis缓存

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

13.3 一级缓存

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

测试步骤:

  1. 开启日志

  2. 测试在一个Session中查询两次记录

        @Test
        public void test1() {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
    
            System.out.println("=====================================");
    
            User user2 =  mapper.getUserById(1);
            System.out.println(user2 == user);
        }
    
    
  3. 查看日志输出

在这里插入图片描述

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

    sqlSession.clearCache();
    

13.4 二级缓存

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

一级缓存开启(SqlSession级别的缓存,也称为本地缓存)

  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
  • 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。

步骤:

  1. 开启全局缓存

    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在Mapper.xml中使用缓存

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    
  3. 测试

    问题:我们需要将实体类序列化,否则就会报错

小结:

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

13.5 缓存原理

在这里插入图片描述

注意:

  • 只有查询才有缓存,根据数据是否需要缓存(修改是否频繁选择是否开启)useCache=“true”

        <select id="getUserById" resultType="user" useCache="true">
            select * from user where id = #{id}
        </select>
    

13.6 自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

​ 1.导包

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

​ 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="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <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"/>

</ehcache>
posted @ 2021-08-10 22:59  你我不在年少  阅读(245)  评论(0编辑  收藏  举报