目录结构
1.maven依赖
添加ehcache、mybatis-ehcache依赖,ehcache依赖slf4j包,所以需要添加slf4j依赖
mybatis提供了二级缓存接口org.apache.ibatis.cache.Cache,mybatis-ehcache的jar包相当于一个适配器,用EhcacheCache调用ehcache的jar,实现Cache接口
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MyBatisTest</artifactId>
<version>1.0-SNAPSHOT</version>
<name>MyBatisTest</name>
<dependencies>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.1</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!--slf4j门面-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!--log4j-slf4j-impl桥接器-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.3</version>
</dependency>
<!--log4j2实现-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<!--mybatis-ehcache-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!--ehcache-->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
</project>
2.数据库配置
在类路径下新建dbconfig.properties文件
username=root
password=root123
jdbcurl=jdbc:mysql://localhost:3306/mybatis_test
driverclass=com.mysql.jdbc.Driver
3.日志文件配置
在类路径下新建log4j2.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" monitorInterval="30">
<Properties>
<Property name="genericPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Properties>
<Appenders>
<Console name="consoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="${genericPattern}" />
</Console>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="consoleAppender"/>
</Root>
<logger name="org.apache.ibatis" level="INFO"></logger>
</Loggers>
</Configuration>
4.mybatis配置
在类路径下新建mybatis-config.xml
添加<setting name="cacheEnabled" value="true"/>
<?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>
<!--resouce:从类路径下开始引用 url:引用磁盘路径或网络路径的资源-->
<properties resource="dbconfig.properties"/>
<settings>
<setting name="logImpl" value="LOG4J2"/>
<!--开启全局缓存开关-->
<setting name="cacheEnabled" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driverclass}"/>
<property name="url" value="${jdbcurl}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="studentDao.xml"/>-->
<!--包扫描,dao接口名与sql映射文件名相同,且放在同一包下-->
<package name="com.example.dao"/>
</mappers>
</configuration>
5、ehcache配置
在类路径下,新建ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="ehcache" updateCheck="false">
<!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<diskStore path="F:\tmpdir"/>
<!-- 设定缓存的默认数据过期策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
diskPersistent="false"
diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
6、JavaBean
public class Clazz {
private Integer cid;
private String cname;
public Clazz() {
}
//set、get方法
//toString方法
}
7、Dao与Mapping
ClazzDao.java
public interface ClazzDao {
public Clazz getClaById(Integer cid);
}
clazzDao.xml
要使用EhcacheCache需添加<cache type="org.mybatis.caches.ehcache.EhcacheCache"></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.example.dao.ClazzDao">
<!--默认的二级缓存-->
<!--<cache></cache>-->
<!--使用EhcacheCache缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
<select id="getClaById" resultType="com.example.bean.Clazz" >
SELECT * FROM t_clazz WHERE cid=#{cid};
</select>
</mapper>
8、测试
public class MyBatisTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void initSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testGetClazz() {
SqlSession openSession1 = null;
try{
openSession1 = sqlSessionFactory.openSession();
ClazzDao clazzDao1 = openSession1.getMapper(ClazzDao.class);
Clazz clazz1 = clazzDao1.getClaById(1);
System.out.println(clazz1);
}finally {
openSession1.close();
}
System.out.println("======================================");
SqlSession openSession2 = null;
try{
openSession2 = sqlSessionFactory.openSession();
ClazzDao clazzDao2 = openSession2.getMapper(ClazzDao.class);
Clazz clazz2 = clazzDao2.getClaById(1);
System.out.println(clazz2);
}finally {
openSession2.close();
}
}
}
结果:
从打印的日志可以看出使用了ehcache,并把数据缓存了