MyBatis 缓存

一级缓存

对于一级缓存来说,Mybatis是直接单个线程隔离的
在执行add,update,delete 的时候,会自动清空缓存,避免脏读造成的影响
此时mapper为线程隔离的,而管理对象为所有线程所共享的.

修改展示层

<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="com.ming.Util.SqlSessionFactoryUtil" %>
<%@ page import="com.ming.MyBatis.RoleMapper" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="com.ming.MyBatis.POJO.Student" %>
<html>
<body>
<h2>Hello World!</h2>

<%
    long startTime = System.currentTimeMillis(); //获取开始时间
    SqlSession sqlSession = null;
    List<Student> students = null;
    List<Student> students1 = null;
        try {
            sqlSession = SqlSessionFactoryUtil.openSqlSesion();
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            students = roleMapper.getStudent(1);
            students1 = roleMapper.getStudent(1);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
    }
    long endTime = System.currentTimeMillis(); //获取结束时间

%>

<%
    Iterator iterator = students.iterator();
    while(iterator.hasNext()){
        %>
            <%=((Student)iterator.next()).getGender()%>

        <%
    }
    iterator = students1.iterator();
    while(iterator.hasNext()){
        %>
            <%=((Student)iterator.next()).getGender()%>
        <%
    }
%>
</body>
</html>

查看日志

2019-04-17 22:33:38.147 [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:136) - Opening JDBC Connection
2019-04-17 22:33:38.147 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:397) - Checked out connection 879027360 from pool.
2019-04-17 22:33:38.148 [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(JdbcTransaction.java:100) - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3464e4a0]
2019-04-17 22:33:38.161 [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:143) - ==>  Preparing: SELECT student.uid, student.gender, student.remarks, student.student_id_number, student.student_name FROM student WHERE student.uid = 1; 
2019-04-17 22:33:38.162 [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:143) - ==> Parameters: 
2019-04-17 22:33:38.181 [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:143) - <==      Total: 1
2019-04-17 22:33:38.183 [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction.resetAutoCommit(JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3464e4a0]
2019-04-17 22:33:38.200 [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction.close(JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3464e4a0]
2019-04-17 22:33:38.201 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.pushConnection(PooledDataSource.java:362) - Returned connection 879027360 to pool.

可以看到只查询了一次

需要注意的是缓存在各个SqlSession是相互隔离的

二级缓存

二级缓存直接添加cache即可

<?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.ming.MyBatis.RoleMapper">
    
    <resultMap type="role" id="roleMap">
        <!-- id为主键映射关系 其中数据库中的id为主键 -->
        <id column="id" property="id" javaType="int" jdbcType="INTEGER"/>
        <!-- result为其他基本数据类型和实体类之间的映射 映射关系为role_name 到 roleName之间的映射 数据类型为string到VARCHAR之间的映射关系 -->
        <result column="role_name" property="roleName" javaType="string" jdbcType="VARCHAR"/>
        <!-- 这里使用typeHandler表示遇到此处理集的时候,将会执行com.ming.MyBatis.StringTypeHandler -->
        <result column="note" property="note" typeHandler="com.ming.MyBatis.StringTypeHandler"/>
    </resultMap>
    
    <select id="getRole" parameterType="int" resultType="com.ming.MyBatis.POJO.Role">
        SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}
    </select>
    
    <select id="findRoleByteMap" parameterType="map" resultMap="roleMap">
        SELECT id, role_name, note FROM t_role
        WHERE role_name LIKE CONCAT('%', #{roleName}, '%')
        AND note LIKE CONCAT('%', #{note}, '%')
    </select>
    
    <select id="findRoleByteMap1" resultMap="roleMap">
        SELECT id, role_name, note FROM t_role
        WHERE role_name LIKE CONCAT('%', #{roleName}, '%')
        AND note LIKE CONCAT('%', #{note}, '%')
    </select>
    
    
    <resultMap id="studentSelfCardMap" type="com.ming.MyBatis.POJO.StudentCard">
        <id column="uid" property="uid"/>
        <result column="student_number" property="studentNumber"/>
        <result column="birthplace" property="birthplace" />
        <result column="date_of_issue" property="dateOfIssue" jdbcType="DATE" javaType="java.util.Date"/>
        <result column="end_date" property="endDate" jdbcType="DATE" javaType="java.util.Date"/>
        <result column="remarks" property="remarks" />
    </resultMap>

    <select id="findStudentSelfCardByStudentId" parameterType="int" resultMap="studentSelfCardMap">
        SELECT student_card.uid, student_card.student_number, student_card.remarks,
        student_card.end_date, student_card.date_of_issue, student_card.birthplace
        FROM student_card WHERE student_card.uid = #{studentId};
    </select>
    
    <resultMap id="studentMap" type="com.ming.MyBatis.POJO.Student">
        <id column="uid" property="uid"/>
        <result column="student_name" property="studentName"/>
        <result column="gender" property="gender"/>
        <result column="student_id_number" property="studentIdNumber"/>
        <result column="remarks" property="remarks"/>
        <!--将会调用接口代表的SQL 进行执行查询 -->
        <association property="studentCard" column="uid" select="com.ming.MyBatis.RoleMapper.findStudentSelfCardByStudentId"/>
    </resultMap>
    
    <select id="getStudent" parameterType="int" resultMap="studentMap">
        SELECT student.uid, student.gender, student.remarks, student.student_id_number,
        student.student_name
        FROM student
        WHERE student.uid = 1;
    </select>
    
    <cache/>
</mapper>

此时select语句将会缓存
insert update delete 将会刷新缓存
会使用LRU算法进行回收
根据时间表 缓存不会用任何时间顺序来刷新缓存
缓存会存储列表集合或对象 1024个引用

由于对象需要序列化所以需要实现 java.io.Serializable接口

父类实现序列化 子类会自动实现序列化 若子类实现序列化 父类没有实现序列化 此时在子类中保存父类的值,直接跳过

2019-04-18 00:55:44.428 [DEBUG] org.apache.ibatis.cache.decorators.LoggingCache.getObject(LoggingCache.java:62) - Cache Hit Ratio [com.ming.MyBatis.RoleMapper]: 0.7586206896551724
2019-04-18 00:55:44.430 [DEBUG] org.apache.ibatis.cache.decorators.LoggingCache.getObject(LoggingCache.java:62) - Cache Hit Ratio [com.ming.MyBatis.RoleMapper]: 0.7666666666666667
2019-04-18 00:55:44.433 [DEBUG] org.apache.ibatis.cache.decorators.LoggingCache.getObject(LoggingCache.java:62) - Cache Hit Ratio [com.ming.MyBatis.RoleMapper]: 0.7741935483870968
2019-04-18 00:55:44.435 [DEBUG] org.apache.ibatis.cache.decorators.LoggingCache.getObject(LoggingCache.java:62) - Cache Hit Ratio [com.ming.MyBatis.RoleMapper]: 0.78125


查看日志,可以发现再次读取的时候,直接从缓存中获取了.
缓存生效,并为执行sql语句

已经命中缓存

自定义缓存

这个需要实现cache接口

package com.ming.MyBatis;

import java.util.concurrent.locks.ReadWriteLock;

/**
 * @author ming
 */
public class Cache implements org.apache.ibatis.cache.Cache {
    /**
     * @return The identifier of this cache
     */
    @Override
    public String getId() {
        return null;
    }

    /**
     * @param key   Can be any object but usually it is a {@link CacheKey}
     * @param value The result of a select.
     */
    @Override
    public void putObject(Object key, Object value) {

    }

    /**
     * @param key The key
     * @return The object stored in the cache.
     */
    @Override
    public Object getObject(Object key) {
        return null;
    }

    /**
     * As of 3.3.0 this method is only called during a rollback
     * for any previous value that was missing in the cache.
     * This lets any blocking cache to release the lock that
     * may have previously put on the key.
     * A blocking cache puts a lock when a value is null
     * and releases it when the value is back again.
     * This way other threads will wait for the value to be
     * available instead of hitting the database.
     *
     * @param key The key
     * @return Not used
     */
    @Override
    public Object removeObject(Object key) {
        return null;
    }

    /**
     * Clears this cache instance.
     */
    @Override
    public void clear() {

    }

    /**
     * Optional. This method is not called by the core.
     *
     * @return The number of elements stored in the cache (not its capacity).
     */
    @Override
    public int getSize() {
        return 0;
    }

    /**
     * Optional. As of 3.2.6 this method is no longer called by the core.
     * <p>
     * Any locking needed by the cache must be provided internally by the cache provider.
     *
     * @return A ReadWriteLock
     */
    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }
}

然后redis直接操作即可

额...暂时先不连接

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容