`
dwj147258
  • 浏览: 192011 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Mybatis一级缓存和二级缓存

阅读更多

mybatis一级缓存二级缓存

 

一级缓存

  Mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言。所以在参数和SQL完全一样的情况下,我们使用同一个SqlSession对象调用一个Mapper方法,往往只执行一次SQL,因为使用SelSession第一次查询后,MyBatis会将其放在缓存中,以后再查询的时候,如果没有声明需要刷新,并且缓存没有超时的情况下,SqlSession都会取出当前缓存的数据,而不会再次发送SQL到数据库。

              

  为什么要使用一级缓存,不用多说也知道个大概。但是还有几个问题我们要注意一下。

  1、一级缓存的生命周期有多长?

  a、MyBatis在开启一个数据库会话时,会 创建一个新的SqlSession对象,SqlSession对象中会有一个新的Executor对象。Executor对象中持有一个新的PerpetualCache对象;当会话结束时,SqlSession对象及其内部的Executor对象还有PerpetualCache对象也一并释放掉。

  b、如果SqlSession调用了close()方法,会释放掉一级缓存PerpetualCache对象,一级缓存将不可用。

  c、如果SqlSession调用了clearCache(),会清空PerpetualCache对象中的数据,但是该对象仍可使用。

  d、SqlSession中执行了任何一个update操作(update()、delete()、insert()) ,都会清空PerpetualCache对象的数据,但是该对象可以继续使用

    2、怎么判断某两次查询是完全相同的查询?

  mybatis认为,对于两次查询,如果以下条件都完全一样,那么就认为它们是完全相同的两次查询。

  2.1 传入的statementId

  2.2 查询时要求的结果集中的结果范围

  2.3. 这次查询所产生的最终要传递给JDBC java.sql.Preparedstatement的Sql语句字符串(boundSql.getSql() )

  2.4 传递给java.sql.Statement要设置的参数值

二级缓存:

  MyBatis的二级缓存是Application级别的缓存,它可以提高对数据库查询的效率,以提高应用的性能。

  MyBatis的缓存机制整体设计以及二级缓存的工作模式

  

 

  SqlSessionFactory层面上的二级缓存默认是不开启的,二级缓存的开席需要进行配置,实现二级缓存的时候,MyBatis要求返回的POJO必须是可序列化的。 也就是要求实现Serializable接口,配置方法很简单,只需要在映射XML文件配置就可以开启缓存了<cache/>,如果我们配置了二级缓存就意味着:

  • 映射语句文件中的所有select语句将会被缓存。
  • 映射语句文件中的所欲insert、update和delete语句会刷新缓存。
  • 缓存会使用默认的Least Recently Used(LRU,最近最少使用的)算法来收回。
  • 根据时间表,比如No Flush Interval,(CNFI没有刷新间隔),缓存不会以任何时间顺序来刷新。
  • 缓存会存储列表集合或对象(无论查询方法返回什么)的1024个引用
  • 缓存会被视为是read/write(可读/可写)的缓存,意味着对象检索不是共享的,而且可以安全的被调用者修改,不干扰其他调用者或线程所做的潜在修改。

实践:

一、创建一个POJO Bean并序列化

  由于二级缓存的数据不一定都是存储到内存中,它的存储介质多种多样,所以需要给缓存的对象执行序列化。(如果存储在内存中的话,实测不序列化也可以的。)

复制代码
package com.yihaomen.mybatis.model;

import com.yihaomen.mybatis.enums.Gender;
import java.io.Serializable;
import java.util.List;

/**
 *  @ProjectName: springmvc-mybatis 
 */
public class Student implements Serializable{

    private static final long serialVersionUID = 735655488285535299L;
    private String id;
    private String name;
    private int age;
    private Gender gender;
    private List<Teacher> teachers;
setters
&getters()....; toString(); }
复制代码

 

 二、在映射文件中开启二级缓存

复制代码
<?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.yihaomen.mybatis.dao.StudentMapper">
    <!--开启本mapper的namespace下的二级缓存-->
    <!--
        eviction:代表的是缓存回收策略,目前MyBatis提供以下策略。
        (1) LRU,最近最少使用的,一处最长时间不用的对象
        (2) FIFO,先进先出,按对象进入缓存的顺序来移除他们
        (3) SOFT,软引用,移除基于垃圾回收器状态和软引用规则的对象
        (4) WEAK,弱引用,更积极的移除基于垃圾收集器状态和弱引用规则的对象。这里采用的是LRU,
                移除最长时间不用的对形象

        flushInterval:刷新间隔时间,单位为毫秒,这里配置的是100秒刷新,如果你不配置它,那么当
        SQL被执行的时候才会去刷新缓存。

        size:引用数目,一个正整数,代表缓存最多可以存储多少个对象,不宜设置过大。设置过大会导致内存溢出。
        这里配置的是1024个对象

        readOnly:只读,意味着缓存数据只能读取而不能修改,这样设置的好处是我们可以快速读取缓存,缺点是我们没有
        办法修改缓存,他的默认值是false,不允许我们修改
    -->
    <cache eviction="LRU" flushInterval="100000" readOnly="true" size="1024"/>
    <resultMap id="studentMap" type="Student">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="gender" column="gender" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler" />
    </resultMap>
    <resultMap id="collectionMap" type="Student" extends="studentMap">
        <collection property="teachers" ofType="Teacher">
            <id property="id" column="teach_id" />
            <result property="name" column="tname"/>
            <result property="gender" column="tgender" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
            <result property="subject" column="tsubject" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
            <result property="degree" column="tdegree" javaType="string" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>
    <select id="selectStudents" resultMap="collectionMap">
        SELECT
            s.id, s.name, s.gender, t.id teach_id, t.name tname, t.gender tgender, t.subject tsubject, t.degree tdegree
        FROM
            student s
        LEFT JOIN
            stu_teach_rel str
        ON
            s.id = str.stu_id
        LEFT JOIN
            teacher t
        ON
            t.id = str.teach_id
    </select>
    <!--可以通过设置useCache来规定这个sql是否开启缓存,ture是开启,false是关闭-->
    <select id="selectAllStudents" resultMap="studentMap" useCache="true">
        SELECT id, name, age FROM student
    </select>
    <!--刷新二级缓存
    <select id="selectAllStudents" resultMap="studentMap" flushCache="true">
        SELECT id, name, age FROM student
    </select>
    -->
</mapper>
复制代码

 

三、在 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>
    <settings>
        <!--这个配置使全局的映射器(二级缓存)启用或禁用缓存-->
        <setting name="cacheEnabled" value="true" />
        .....
    </settings>
    ....
</configuration>
复制代码

 

四、测试

复制代码
package com.yihaomen.service.student;

import com.yihaomen.mybatis.dao.StudentMapper;
import com.yihaomen.mybatis.model.Student;
import com.yihaomen.mybatis.model.Teacher;
import com.yihaomen.service.BaseTest;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;

/**
 *   
 *  @ProjectName: springmvc-mybatis 
 */
public class TestStudent extends BaseTest {

    public static void selectAllStudent() {
        SqlSessionFactory sqlSessionFactory = getSession();
        SqlSession session = sqlSessionFactory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        List<Student> list = mapper.selectAllStudents();
        System.out.println(list);
        System.out.println("第二次执行");
        List<Student> list2 = mapper.selectAllStudents();
        System.out.println(list2);
        session.commit();
        System.out.println("二级缓存观测点");
        SqlSession session2 = sqlSessionFactory.openSession();
        StudentMapper mapper2 = session2.getMapper(StudentMapper.class);
        List<Student> list3 = mapper2.selectAllStudents();
        System.out.println(list3);
        System.out.println("第二次执行");
        List<Student> list4 = mapper2.selectAllStudents();
        System.out.println(list4);
        session2.commit();

    }

    public static void main(String[] args) {
        selectAllStudent();
    }
}
复制代码

 

结果:

[QC] DEBUG [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(98) | Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@51e0173d]
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | ==> Preparing: SELECT id, name, age FROM student 
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | ==> Parameters: 
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(139) | <== Total: 6
[Student{id='1', name='刘德华', age=55, gender=null, teachers=null}, Student{id='2', name='张惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='谢霆锋', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
第二次执行
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.0
[Student{id='1', name='刘德华', age=55, gender=null, teachers=null}, Student{id='2', name='张惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='谢霆锋', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
二级缓存观测点
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.3333333333333333
[Student{id='1', name='刘德华', age=55, gender=null, teachers=null}, Student{id='2', name='张惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='谢霆锋', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]
第二次执行
[QC] DEBUG [main] org.apache.ibatis.cache.decorators.LoggingCache.getObject(62) | Cache Hit Ratio [com.yihaomen.mybatis.dao.StudentMapper]: 0.5
[Student{id='1', name='刘德华', age=55, gender=null, teachers=null}, Student{id='2', name='张惠妹', age=49, gender=null, teachers=null}, Student{id='3', name='谢霆锋', age=35, gender=null, teachers=null}, Student{id='4', name='王菲', age=47, gender=null, teachers=null}, Student{id='5', name='汪峰', age=48, gender=null, teachers=null}, Student{id='6', name='章子怡', age=36, gender=null, teachers=null}]

Process finished with exit code 0

 

我们可以从结果看到,sql只执行了一次,证明我们的二级缓存生效了。

 

分享到:
评论

相关推荐

    mybatis一级缓存和二级缓存简单示例

    本文将深入讲解 MyBatis 的一级缓存和二级缓存,并通过一个简单的示例进行说明。 ### 一级缓存 一级缓存是 Session 级别的缓存,也称为本地缓存(Local Cache)。每当我们在一个 SqlSession 中执行了 CRUD 操作,...

    深入理解MyBatis中的一级缓存与二级缓存

    下面我们将深入了解MyBatis中的一级缓存和二级缓存。 一级缓存 一级缓存是SqlSession级别的缓存。它是在操作数据库时构造的SqlSession对象中维护的一个数据结构,用于存储缓存数据。不同的SqlSession之间的缓存...

    mybatis二级缓存学习

    总结,MyBatis二级缓存是一项实用的性能优化技术,但使用时需注意其工作原理和潜在的问题,合理配置和管理才能发挥最大效能。通过理解和实践,我们可以更好地掌握这一工具,提高应用的运行效率。

    springMybatis+redis三级缓存框架

    综上所述,"springMybatis+redis三级缓存框架"是一种有效的优化方案,它结合了MyBatis的二级缓存和Redis的分布式缓存能力,能够在保证系统响应速度的同时,降低数据库的负载,提升整体应用性能。在实际应用中,根据...

    MyBatis缓存(一级缓存、二级缓存)

    缓存是MyBatis性能优化的重要手段,分为一级缓存和二级缓存。在这篇文章中,我们将深入探讨这两个级别的缓存机制及其工作原理。 **一级缓存** 一级缓存是SqlSession级别的缓存,也称为局部缓存。当你执行一个查询...

    Mybatis的以及缓存和二级缓存(案例).mhtml

    此文章是对Mybatis框架的一级缓存一级二级缓存的描述,包括他们的作用,案例,以及部分源码分析,对一级缓存以及二级缓存进行了详细的描述以及概括,还有如何使用等内容

    mybatis二级缓存

    标题中的“mybatis二级缓存”指的是MyBatis框架中的一个重要特性,它是MyBatis缓存机制的一部分,用于提升数据库查询效率。MyBatis一级缓存是SqlSession级别的,而二级缓存则是在整个Mapper配置范围内的全局缓存,...

    从0到1项目搭建-集成 Redis 配置MyBatis二级缓存

    基于 SpringBoot 从0搭建一个企业级开发项目,基于SpringBoot 的项目,并集成MyBatis-Plus、Redis、Druid、Logback ,并使用 Redis 配置 MyBatis 二级缓存。

    mybatis一二级缓存

    在 MyBatis 中,一级缓存和二级缓存是两个重要的性能优化手段,它们可以有效减少对数据库的访问,提高系统的响应速度。下面将详细阐述这两个缓存机制。 ### 一级缓存 一级缓存是 MyBatis 默认开启的本地会话缓存,...

    mybatis二级缓存扩展-与redis集成

    集成Redis作为二级缓存的优势在于,Redis是一款高效的内存数据结构存储系统,支持多种数据结构如字符串、哈希、列表、集合和有序集合,适合用于缓存。此外,Redis支持主从复制和集群部署,能提供高可用性和数据持久...

    MyBatis 二级缓存 关联刷新实现

    MyBatis 二级缓存 关联刷新实现1、MyBatis缓存介绍2、二级缓存问题2.1、数据不一致问题验证2.2、问题处理思路3、关联缓存刷新实现 1、MyBatis缓存介绍  Mybatis提供对缓存的支持,但是在没有配置的默认情况下,它只...

    深入了解MyBatis二级缓存

    "深入了解MyBatis二级缓存...MyBatis二级缓存是一种强大的缓存机制,可以提高应用程序的性能和可扩展性。通过了解MyBatis二级缓存的工作原理、配置方法和使用场景,可以更好地使用MyBatis二级缓存提高应用程序的性能。

    MyBatis3开启二级缓存

    MyBatis的缓存分为一级缓存和二级缓存。一级缓存是SqlSession级别的,同一个SqlSession内的相同SQL语句不会重复执行,而是直接从缓存中获取结果。然而,一级缓存存在生命周期问题,当SqlSession关闭时,一级缓存就会...

    mybatis一级二级缓存流程图.drawio

    mybatis一级二级缓存流程图.drawio mybatis一级二级缓存流程图.drawio mybatis一级二级缓存流程图.drawio mybatis一级二级缓存流程图.drawio

    mybatis-plus 缓存(二)

    作为一名 IT 行业大师,我将对 Mybatis-Plus 缓存机制进行详细的解释,帮助读者深入了解缓存的概念、Mybatis-Plus 缓存机制的工作原理、一级缓存和二级缓存的配置和使用、缓存的优点和缺点等。 缓存是什么? 缓存是...

    深入了解MyBatis二级缓存共6页.pdf.zip

    本文将深入探讨MyBatis的二级缓存机制,旨在帮助开发者更好地理解和利用这一功能。 首先,我们需要了解什么是缓存。缓存是一种存储技术,用于暂时保存经常访问的数据,以便快速获取,减少对数据库的直接访问,从而...

    MyBatis-05 缓存机制

    本篇文章将详细探讨MyBatis的缓存机制,包括一级缓存和二级缓存,以及如何将MyBatis与第三方缓存EhCache进行整合。 首先,我们来了解一级缓存。一级缓存是SqlSession级别的,也称为本地缓存。当我们在一个...

    Mybatis-plus基于redis实现二级缓存过程解析

    Mybatis-plus基于Redis实现二级缓存过程解析 Mybatis-plus是一款基于Java语言的持久层框架,旨在简化数据库交互操作。然而,在高并发、高性能的应用场景中,数据库的查询操作可能会成为性能瓶颈。为了解决这个问题...

    mybatis+redis缓存配置

    MyBatis提供了两种级别的缓存支持:一级缓存和二级缓存。 - **一级缓存**:也称为本地会话缓存,它的生命周期是伴随着一次会话(SqlSession)的开始和结束。一级缓存默认开启且无法关闭,主要用于减少同一个会话内...

    mybatis二级缓存的实现代码

    MyBatis二级缓存的实现代码主要是通过在总的配置文件中设置开启二级缓存,在每个映射XML文件中添加useCache="true"标签,并在Java实体类中实现一个系列化接口。通过使用MyBatis二级缓存,可以减少数据库的查询次数,...

Global site tag (gtag.js) - Google Analytics