前言:
什么是Mybatis缓存?
使用缓存可以减少Java Application与数据库的交互次数,从而提升程序的运行效率。比如,查询id=1的user对象,第一次查询出来之后,会自动将该对象保存到缓存中。下一次查询该对象时,就可以直接从缓存中获取,不需要发送SQL查询数据库了。
Mybatis缓存分类
一级缓存:SqlSession级别,默认开启,且不能关闭。
mybatis的一级缓存是SqlSession级别的缓存,在操作数据库时需要构造SqlSession对象,在对象中有一个HashMap用于存储缓存数据,不同的SqlSession之间缓存数据区域(HashMap)是互相不影响的。
一级缓存的作用域是SqlSession范围的,当在同一个SqlSession中执行两次相同的sql语句时,第一次执行完毕会将数据库中查询的数据写到缓存(内存)中,第二次查询时会从缓存中获取数据,不再去底层进行数据库查询,从而提高了查询效率。需要注意的是:如果SqlSession执行了DML操作(insert、update、delete),并执行commit()操作,mybatis则会清空SqlSession中的一级缓存,这样做的目的是为了保证缓存数据中存储的是最新的信息,避免出现脏读现象。
当一个SqlSession结束后该SqlSession中的一级缓存也就不存在了,Mybatis默认开启一级缓存,不需要进行任何配置。
二级缓存:Mapper级别,默认关闭,可以开启。
二级缓存是Mapper级别的缓存,使用二级缓存时,多个SqlSession使用同一个Mapper的sql语句去操作数据库,得到的数据会存在二级缓存区域,它同样是使用HashMapper进行数据存储,相比一级缓存SqlSession,二级缓存的范围更大,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。
二级缓存是多个SqlSession共享的,其作用域是mapper的同一个namespace,不同的SqlSession两次执行相同的namespace下的sql语句,且向sql中传递的参数也相同,即最终执行相同的sql语句,则第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次查询时会从缓存中获取数据,不再去底层数据库查询,从而提高查询效率。
Mybatis默认关闭二级缓存,可以在setting全局参数中配置开启二级缓存。
下面我们通过代码来学习如何使用MyBatis缓存。
代码:
首先来演示一级缓存,以查询User对象为例。
1.User实体类
package com.southwind.entity;
public class User{
private int id;
private String username;
private String password;
private int age;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
}
2.UserDAO接口
package com.southwind.dao;
import com.southwind.entity.User;
public interface UserDAO {
public User get(int id);
}
3.UserDAO.xml
<mapper namespace="com.southwind.dao.UserDAO">
<select id="get" parameterType="int" resultType="user">
select * from user where id = #{id}
select>
mapper>
4.config.xml
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<typeAlias type="com.southwind.entity.User" alias="user"/>
typeAliases>
<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/mybatis?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/southwind/dao/StudentDAO.xml"/>
mappers>
configuration>
5.Test测试类
package com.southwind.test;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.southwind.dao.UserDAO;
import com.southwind.entity.User;
public class Test {
public static void main(String[] args) {
InputStream is = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
//一级缓存
User user2 = userDAO.get(22);
System.out.println(user2);
User user3 = userDAO.get(22);
System.out.println(user3);
}
}
可以看到结果,执行了一次SQL语句,查询出两个对象,第一个对象是通过SQL查询的,并保存到缓存中,第二个对象是直接从缓存中获取的。
我们说过一级缓存是SqlSession级别的,所以SqlSession一旦关闭,缓存也就不复存在了,修改代码,再次测试。
package com.southwind.test;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.southwind.dao.UserDAO;
import com.southwind.entity.User;
public class Test {
public static void main(String[] args) {
InputStream is = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
//一级缓存
User user2 = userDAO.get(22);
System.out.println(user2);
sqlSession.close();
sqlSession = sqlSessionFactory.openSession();
userDAO = sqlSession.getMapper(UserDAO.class);
User user3 = userDAO.get(22);
System.out.println(user3);
}
}
可以看到,执行了两次SQL。
在关闭SqlSession,一级缓存失效的情况下,可以启用二级缓存,实现提升效率的要求。
MyBatis可以使用自带的二级缓存,也可以使用第三方的ehcache二级缓存。
自带二级缓存
1.config.xml中配置开启二级缓存。
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
settings>
<typeAliases>
<typeAlias type="com.southwind.entity.User" alias="user"/>
typeAliases>
<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/mybatis?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/southwind/dao/StudentDAO.xml"/>
mappers>
configuration>
2.UserDAO.xml中配置二级缓存。
<mapper namespace="com.southwind.dao.UserDAO">
<cache>cache>
<select id="get" parameterType="int" resultType="user">
select * from user where id = #{id}
select>
mapper>
3.User实现Serializable接口。
package com.southwind.entity;
import java.io.Serializable;
public class User implements Serializable{
private int id;
private String username;
private String password;
private int age;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
}
4.测试。
package com.southwind.test;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.southwind.dao.UserDAO;
import com.southwind.entity.User;
public class Test {
public static void main(String[] args) {
InputStream is = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
//一级缓存
User user2 = userDAO.get(22);
System.out.println(user2);
sqlSession.close();
sqlSession = sqlSessionFactory.openSession();
userDAO = sqlSession.getMapper(UserDAO.class);
User user3 = userDAO.get(22);
System.out.println(user3);
}
}
可以看到,执行了一次SQL,查询出两个对象。
ehcache二级缓存
1.添加ehcache依赖jar包。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.southwindgroupId>
<artifactId>ehcacheartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>ehcacheMaven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.25version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.0.0version>
dependency>
dependencies>
<build>
<finalName>ehcachefinalName>
build>
project>
2.添加ehcache.xml。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
defaultCache>
ehcache>
3.config.xml中配置开启二级缓存。
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
settings>
<typeAliases>
<typeAlias type="com.southwind.entity.User" alias="user"/>
typeAliases>
<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/mybatis?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/southwind/dao/StudentDAO.xml"/>
mappers>
configuration>
4.UserDAO.xml中配置二级缓存。
<mapper namespace="com.southwind.dao.UserDAO">
<cache type="org.mybatis.caches.ehcache.EhcacheCache" >
<property name="timeToIdleSeconds" value="3600"/>
<property name="timeToLiveSeconds" value="3600"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
cache>
<select id="get" parameterType="int" resultType="user">
select * from user where id = #{id}
select>
mapper>
5.User不需要实现Serializable接口。
package com.southwind.entity;
public class User{
private int id;
private String username;
private String password;
private int age;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
}
6.测试。
package com.southwind.test;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.southwind.dao.UserDAO;
import com.southwind.entity.User;
public class Test {
public static void main(String[] args) {
InputStream is = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
//一级缓存
User user2 = userDAO.get(22);
System.out.println(user2);
sqlSession.close();
sqlSession = sqlSessionFactory.openSession();
userDAO = sqlSession.getMapper(UserDAO.class);
User user3 = userDAO.get(22);
System.out.println(user3);
}
}