MyBatis研习录(13)——MyBatis二级缓存


C语言自学完备手册(33篇)

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

MySQL数据库实操教程(35篇图文版)

推翻自己和过往——自定义View系列教程(10篇)

走出思维困境,踏上精进之路——Android开发进阶精华录

讲给Android程序员看的前端系列教程(40集免费视频教程+源码)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

使用二级缓存的前期准备

在MyBatis中使用二级缓存之前,需要进行如下配置:

1、在mybatis-config.xml中开启二级缓存

  <settings>
    <!-- 开启二级缓存 -->
	<setting name="cacheEnabled" value="true"/>
  </settings>

2、xxxMapper.xml中使用catch标签

<!-- 使用二级缓存 -->
<cache></cache>

3、pojo实现Serializable接口

public class YourPojo implements Serializable{ }

二级缓存的使用说明

当MyBatis中开启二级缓存,那么缓存的使用顺序如下:

  • 1、当执行查询语句时候会先去二级缓存中查询数据,如果有则返回。如果二级缓存中没有则到一级缓存中查找。
  • 2、如果一级缓存中有,则返回。如果一级缓存也没有则发送sql语句到数据库中去查询。
  • 3、从数据库查询出数据后立马将数据保存到一级缓存中。
  • 4、当SqlSession关闭的时候把一级缓存中的数据保存到二级缓存中。

请注意:如果执行增 、删、改 那么会同时清除一级缓存和二级缓存

二级缓存使用示例

数据准备

DROP DATABASE IF EXISTS mybatisDatabase;
CREATE DATABASE mybatisDatabase;
use mybatisDatabase;
CREATE TABLE user(
  id INT PRIMARY KEY auto_increment,
  username VARCHAR(50),
  password VARCHAR(50),
  gender VARCHAR(10)
);

INSERT INTO user(username,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(username,password,gender) VALUES("momo","234567","female");
INSERT INTO user(username,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(username,password,gender) VALUES("pepe","456123","female");

SELECT * FROM user;

搭建开发环境

创建普通的Java工程,结构如下:
在这里插入图片描述

User

package cn.com.pojo;

import java.io.Serializable;

/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User implements Serializable{
	private static final long serialVersionUID = 112149170027586026L;
	private Integer id;
	private String username;
	private String password;
	private String gender;
	public User() {
		
	}

	public User(Integer id, String username, String password, String gender) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.gender = gender;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", gender=" + gender + "]";
	}
	
}

UserMapper .java

package cn.com.mapper;

import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserMapper {
	
	public User queryUserById(Integer id);
	
	public int updateUser(User user);
}

UserMapper .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="cn.com.mapper.UserMapper">	

  <!-- 使用二级缓存 -->
  <cache></cache>
  
  <select id="queryUserById" parameterType="java.lang.Integer" resultType="cn.com.pojo.User">
    select id,username,password,gender from user where id = #{id}
  </select>
  
  <update id="updateUser" parameterType="cn.com.pojo.User">
     update user set username=#{username},password=#{password},gender=#{gender} where id=#{id}
  </update>
  
</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>
  
  <!-- 配置数据源 -->
  <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/mybatisDatabase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 配置mapper -->
  <mappers>
    <mapper resource="cn/com/pojo/UserMapper.xml"/>
  </mappers>
  
</configuration>

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

MybatisTest

package cn.com.test;

import java.io.InputStream;
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 org.junit.Test;
import cn.com.mapper.UserMapper;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class MybatisTest {

	static SqlSessionFactory sqlSessionFactory = null;

	public static SqlSessionFactory getSqlSessionFactory() {
		try {
			if (sqlSessionFactory == null) {
				InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
			}
			return sqlSessionFactory;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {

		}
		return null;
	}
	
	public void sqlSessionCatch() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据查询
		User user = userMapper.queryUserById(1);
		System.out.println(user.getUsername());
		//关闭SqlSession
		sqlSession.close();
	}
	@Test
	public void testSqlSessionCatch() {
		sqlSessionCatch();
		sqlSessionCatch();
		sqlSessionCatch();
		sqlSessionCatch();
	}
	
	public void sqlSessionCatchClean() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据查询
		User user = userMapper.queryUserById(1);
		System.out.println(user.getUsername());
		//利用SqlSession执行数据更新
		userMapper.updateUser(new User(2, "bmbm", "123456", "female"));
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testSqlSessionCatchClean() {
		sqlSessionCatchClean();
		sqlSessionCatchClean();
		sqlSessionCatchClean();
		sqlSessionCatchClean();
	}

}

testSqlSessionCatch测试结果如下:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.0
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1392425346.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - ==>  Preparing: select id,username,password,gender from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
lucy
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Returned connection 1392425346 to pool.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.5
lucy
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.6666666666666666
lucy
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.75
lucy

请注意命中率Cache Hit Ratio的变化:

  • 1、第一次查询时无缓存,所以Cache Hit Ratio=0
  • 2、第二次查询时有缓存,共两次查询其中一次来自于缓存;所以,Cache Hit Ratio=0.5
  • 3、第三次查询时有缓存,共三次查询其中二次来自于缓存;所以,Cache Hit Ratio=0.66666666666666666666
  • 4、第四次查询时有缓存,共四次查询其中三次来自于缓存;所以,Cache Hit Ratio=0.75

testSqlSessionCatchClean测试结果如下:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.0
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1392425346.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - ==>  Preparing: select id,username,password,gender from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
lucy
DEBUG [main] - ==>  Preparing: update user set username=?,password=?,gender=? where id=? 
DEBUG [main] - ==> Parameters: bmbm(String), 123456(String), female(String), 2(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Returned connection 1392425346 to pool.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.0
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Checked out connection 1392425346 from pool.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - ==>  Preparing: select id,username,password,gender from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
lucy
DEBUG [main] - ==>  Preparing: update user set username=?,password=?,gender=? where id=? 
DEBUG [main] - ==> Parameters: bmbm(String), 123456(String), female(String), 2(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Returned connection 1392425346 to pool.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.0
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Checked out connection 1392425346 from pool.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - ==>  Preparing: select id,username,password,gender from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
lucy
DEBUG [main] - ==>  Preparing: update user set username=?,password=?,gender=? where id=? 
DEBUG [main] - ==> Parameters: bmbm(String), 123456(String), female(String), 2(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Returned connection 1392425346 to pool.
DEBUG [main] - Cache Hit Ratio [cn.com.mapper.UserMapper]: 0.0
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Checked out connection 1392425346 from pool.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - ==>  Preparing: select id,username,password,gender from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
lucy
DEBUG [main] - ==>  Preparing: update user set username=?,password=?,gender=? where id=? 
DEBUG [main] - ==> Parameters: bmbm(String), 123456(String), female(String), 2(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@52feb982]
DEBUG [main] - Returned connection 1392425346 to pool.

在此测试中命中率Cache Hit Ratio=0;再次验证了:如果执行增 、删、改 那么会同时清除一级缓存和二级缓存

二级缓存策略

MyBatis二级缓存常用策略如下:

• LRU – 最近最少使用的,即移除最长时间不被使用的对象(默认策略)。
• FIFO – 先进先出,即按对象进入缓存的顺序来移除它们。
• SOFT – 软引用,即移除基于垃圾回收器状态和软引用规则的对象。
• WEAK – 弱引用,即更积极地移除基于垃圾收集器状态和弱引用规则的对象。

发布了1019 篇原创文章 · 获赞 1913 · 访问量 233万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览