1:所需要的配置文件和需要配的东西如下
(1)maven
<!-- ehcache与mybatis整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.0.0.m3</version>
</dependency>
注意:这里可能会有依赖冲突,ehcache里面有lsf4j-api 可能会跟其他东西冲突,遇到问题请自行解决依赖问题。
(2)spring 配置
<!-- 开启spring缓存 -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
<cache:annotation-driven cache-manager="cacheManager" />
一般配这里两个再加上复制来的ehcache.xml文件是没问题的,但是遇到过许多问题异常下面整理
2:异常展示
(1):Error creating bean with name 'ehcache' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Error configuring from input stream. Initial cause was Invalid byte 1 of 1-byte UTF-8 sequence.
这里关键是看最后面的东西,刚开始觉得很莫名其妙跟编码有什么关系,后面将ehcache.xml中文注释给删了才好,真是的注释都不能用中文。
(2):Error creating bean with name 'ehcache' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: net.sf.ehcache.CacheManager.create(Lnet/sf/ehcache/config/Configuration;)Lnet/sf/ehcache/CacheManager;
一般NoSuchMethodError都是因为没找到类跟导包有原因,而这里是因为加上了<property name="shared" value="true"></property> 这玩意,这里原因没具体研究大概就是有两个CacheManager的方法 我们可以用默认的 然后我们加了这句就是去另外个没导进来的里面去找了 ,目前关于ehcache+mybatis的整合出现的问题就这两种。
然后用法的话很简单:就是在mabaits dao的xml文件上面加上一 <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> 这个是有日志的那种 还有句是没有日志的,然后如果有的不想要缓存的话 在sql上面加上useCache="false"取消就好了。