mybatis一级缓存与二级缓存

一、环境搭建

目录结构

1.maven依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>MyBatisTest</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>MyBatisTest</name>

  <dependencies>

    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>

    <!--mysql-connector-java-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.1</version>
    </dependency>

    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>

    <!--slf4j门面-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>

    <!--log4j-slf4j-impl桥接器-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>2.3</version>
    </dependency>

    <!--log4j2实现-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.7</version>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.7</version>
    </dependency>

  </dependencies>

</project>

2.数据库配置

在类路径下新建dbconfig.properties文件

username=root
password=root123
jdbcurl=jdbc:mysql://localhost:3306/mybatis_test
driverclass=com.mysql.jdbc.Driver

3.日志文件配置

在类路径下新建log4j2.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" monitorInterval="30">
    <Properties>
        <Property name="genericPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    </Properties>

    <Appenders>
        <Console name="consoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="${genericPattern}" />
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="consoleAppender"/>
        </Root>
        <logger name="org.apache.ibatis" level="INFO"></logger>
    </Loggers>
</Configuration>

4.mybatis配置

在类路径下新建mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--resouce:从类路径下开始引用 url:引用磁盘路径或网络路径的资源-->
    <properties resource="dbconfig.properties"/>

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

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

    <mappers>
        <!--<mapper resource="studentDao.xml"/>-->
        <!--包扫描,dao接口名与sql映射文件名相同,且放在同一包下-->
        <package name="com.example.dao"/>
    </mappers>

</configuration>

5.JavaBean

Clazz.java

public class Clazz {
    private Integer cid;
    private String cname;

    public Clazz() {
    }
    
    //set、get方法
    //toString方法
}

7、Dao与Mapping

ClazzDao.java

public interface ClazzDao {

    public Clazz getClaById(Integer cid);

}

clazzDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.ClazzDao">

    <select id="getClaById" resultType="com.example.bean.Clazz" >
        SELECT * FROM t_clazz WHERE cid=#{cid};
    </select>

</mapper>

二、一级缓存

 

一级缓存:SqlSession级别的缓存,默认存在的

机制:只有之前查询过的数据,mybatis就会保存在一个缓存中(Map);下次获取直接从缓存中拿;

一级缓存失效的几种情况:

  1. 不同的SqlSession,使用不同的一级缓存
  2. 同一个方法,不同的参数,由于可能之前没有查询过,所以还会发新的sql
  3. 在这个sqlsssion期间执行上任何一次增删改操作,增删改会把缓存清空
  4. 手动清空缓存

测试类:

public class MyBatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void initSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testGetClazz() {
        SqlSession openSession = null;
        try{
            openSession = sqlSessionFactory.openSession();

            ClazzDao clazzDao = openSession.getMapper(ClazzDao.class);

            Clazz clazz1 = clazzDao.getClaById(1);
            System.out.println(clazz1);

            System.out.println("=======================");

            Clazz clazz2 = clazzDao.getClaById(1);
            System.out.println(clazz2);

        }finally {
            openSession.close();
        }
    }

}

结果:

从打印日志可以看出,只查询了一次数据库

三、二级缓存

二级缓存:二级缓存在SqlSessiion关闭或提交以后,一级缓存数据会放到二级缓存

缓存查询顺序:不会出现一级缓存和二级缓存中有同一个数据;任何时候先看二级缓存,再看一级缓存,如果都没有就去查询数据库    

实现二级缓存步骤:

  1. mybatis配置:开启一级缓存<setting name="cacheEnabled" value="true"/>(<configuration>下<settings>添加<setting>标签)
  2. mapping配置:<cache></cache> (<mapper>下添加<cache>)
  3. javabean配置:javabean实现Serializable序列化

测试类:

public class MyBatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void initSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testGetClazz() {
        SqlSession openSession1 = null;
        try{
            openSession1 = sqlSessionFactory.openSession();

            ClazzDao clazzDao1 = openSession1.getMapper(ClazzDao.class);

            Clazz clazz1 = clazzDao1.getClaById(1);
            System.out.println(clazz1);

        }finally {
            openSession1.close();
        }

        System.out.println("======================================");

        SqlSession openSession2 = null;
        try{
            openSession2 = sqlSessionFactory.openSession();

            ClazzDao clazzDao2 = openSession2.getMapper(ClazzDao.class);

            Clazz clazz2 = clazzDao2.getClaById(1);
            System.out.println(clazz2);

        }finally {
            openSession2.close();
        }
    }

}

结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值