Mybatis整合ehcache
1.首先引入jar包
1).ehcache的核心包
2).mybatis和ehcache的整合包(实现了mybatis的cache接口等等)
3).日志打印包
这三个jar包,从http://www.mybatis.org/ehcache-cache/这个官网下载就可以了
2.mapper.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="com.dao.MemberMapperEhCache"> <!-- 引入自定义缓存ehCache --> <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> <select id="selectMembersById" resultType="members"> select * from members where id = #{id} </select> </mapper>
3.在类路径下,引入ehcache.xml
默认的配置就好
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <diskStore path="D:\ehcache"></diskStore> <!-- 默认缓存配置 --> <defaultCache maxElementsInMemory="0" maxElementsOnDisk="10" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> </ehcache>
4.测试
public static void main(String[] args) throws IOException { // 获取两个不同的session SqlSession session1 = getSqlSession(); SqlSession session2 = getSqlSession(); try { // 获取两个不同的mapper MemberMapperEhCache mapper1 = session1.getMapper(MemberMapperEhCache.class); MemberMapperEhCache mapper2 = session2.getMapper(MemberMapperEhCache.class); // 获取id为1的对象 Members member1 = mapper1.selectMembersById(1); System.out.println(member1.toString()); session1.close(); // 获取id为1的对象 Members member2 = mapper2.selectMembersById(1); System.out.println(member2.toString()); session2.close(); } finally { } } public static SqlSession getSqlSession() throws IOException { // 读取全局配置文件 String resource = "conf/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 获取sqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 打开session SqlSession session = sqlSessionFactory.openSession(); return session; }
5.结果
Created connection 331510866. Returned connection 331510866 to pool. Cache Hit Ratio [com.dao.MemberMapperEhCache]: 0.0 Opening JDBC Connection Checked out connection 754666084 from pool. Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2cfb4a64] ==> Preparing: select * from members where id = ? ==> Parameters: 1(Integer) <== Columns: id, member_name, age, gender, email <== Row: 1, jack, 25, 1, jack@beijing.com <== Total: 1 Members [id=1, member_name=jack, age=25, gender=1, email=jack@beijing.com] Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2cfb4a64] Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2cfb4a64] Returned connection 754666084 to pool. Cache Hit Ratio [com.dao.MemberMapperEhCache]: 1.0 Members [id=1, member_name=jack, age=25, gender=1, email=jack@beijing.com]
两个不同的sqlSession,只发送一条sql语句,使用ehcache成功!