mybatis一級緩存二級緩存

一級緩存

  Mybatis對緩存提供支持,可是在沒有配置的默認狀況下,它只開啓一級緩存,一級緩存只是相對於同一個SqlSession而言。因此在參數和SQL徹底同樣的狀況下,咱們使用同一個SqlSession對象調用一個Mapper方法,每每只執行一次SQL,由於使用SelSession第一次查詢後,MyBatis會將其放在緩存中,之後再查詢的時候,若是沒有聲明須要刷新,而且緩存沒有超時的狀況下,SqlSession都會取出當前緩存的數據,而不會再次發送SQL到數據庫。html

              

  爲何要使用一級緩存,不用多說也知道個大概。可是還有幾個問題咱們要注意一下。java

  一、一級緩存的生命週期有多長?mysql

  a、MyBatis在開啓一個數據庫會話時,會 建立一個新的SqlSession對象,SqlSession對象中會有一個新的Executor對象。Executor對象中持有一個新的PerpetualCache對象;當會話結束時,SqlSession對象及其內部的Executor對象還有PerpetualCache對象也一併釋放掉。git

  b、若是SqlSession調用了close()方法,會釋放掉一級緩存PerpetualCache對象,一級緩存將不可用。算法

  c、若是SqlSession調用了clearCache(),會清空PerpetualCache對象中的數據,可是該對象仍可以使用。spring

  d、SqlSession中執行了任何一個update操做(update()、delete()、insert()) ,都會清空PerpetualCache對象的數據,可是該對象能夠繼續使用sql

    二、怎麼判斷某兩次查詢是徹底相同的查詢?數據庫

  mybatis認爲,對於兩次查詢,若是如下條件都徹底同樣,那麼就認爲它們是徹底相同的兩次查詢。apache

  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(可讀/可寫)的緩存,意味着對象檢索不是共享的,並且能夠安全的被調用者修改,不干擾其餘調用者或線程所作的潛在修改。

實踐:

1、建立一個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(); }

 

 2、在映射文件中開啓二級緩存

<?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>

 

3、在 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>

 

4、測試

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只執行了一次,證實咱們的二級緩存生效了。

 

https://gitee.com/huayicompany/springmvc-mybatis

參考:

[1]楊開振 著,《深刻淺出MyBatis技術原理與實戰》, 電子工業出版社,2016.09

[2]博客,http://blog.csdn.net/luanlouis/article/details/41280959

[3]博客,http://www.cnblogs.com/QQParadise/articles/5109633.html

[4]博客,http://blog.csdn.net/isea533/article/details/44566257

相關文章
相關標籤/搜索