一、导入相关jar
<!-- mybatis 整合ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
二、使用的一些配置
1、SqlMapConfig.xml 全局配置文件中开启缓存配置。
<settings>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
2、对应要开启的mapper.xml中引入ehcache缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
3、加入ehcache的配置文件ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="D:\ehcache" />
<defaultCache
eternal="false"
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
然后就可以把ehcache当做mybatis的二级缓存来使用了。
三、出现的异常信息
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.NullPointerException
### Cause: java.lang.NullPointerException
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:114)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:58)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
at com.sun.proxy.$Proxy5.findOrder2(Unknown Source)
at com.itcaq.TestOrder2.testFindOrder2(TestOrder2.java:92)
......
四、原因查找
看异常信息,发现我们自己写的代码出错在这
at com.itcaq.TestOrder2.testFindOrder2(TestOrder2.java:92)
往上看,发现
at com.sun.proxy.$Proxy5.findOrder2(Unknown Source)
这就是说明mapper.xml根本没有加载进来
原因:经过多次测试,发现mybatis-ehcache 1.1.0 这个版本就是不可以的。
(虽然简单,具体为什么不可以,也还没来得及细细分析,先将问题爆出来,有遇到同样问题的同行可以少走些弯路。)
五、解决办法
将mybatis-ehcache 1.1.0 换成 mybatis-ehcache 1.0.3 或者以下都可以。