1)Mybatis配置文件及config.properties文件
在mybatis-config.xml中配置
<properties resource="config.properties"></properties>
<settings>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
在config.properties配置
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:XE
username=test
password=test
2)Mybatis映射接口和映射文件
3)Jedis相关配置文件和工具类
src下面的config.properties
封装Jedis的工具类
JedisUtils.java
SerializingUtils.java
封装MyBatis的工具类
MyBatisSqlSessionFactory.java
4)自定义cache接口实现类MybatisRedisCache.java
package com.briup.cache;
import java.util.concurrent.locks.ReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;
import com.briup.util.JedisUtils;
import redis.clients.jedis.Jedis;
public class MybatisRedisCache implements Cache{
private String id;
public MybatisRedisCache(String id) {
this.id = id;
}
@Override
public void clear() {
JedisUtils.clear();
}
@Override
public String getId() {
return this.id;
}
@Override
public Object getObject(Object key) {
return JedisUtils.get(key);
}
@Override
public ReadWriteLock getReadWriteLock() {
return null;
}
@Override
public int getSize() {
return JedisUtils.getSize();
}
@Override
public void putObject(Object key, Object value) {
JedisUtils.set(key, value);
}
@Override
public Object removeObject(Object key) {
return null;
}
@Override
public boolean equals(Object o) {
if (getId() == null)
throw new CacheException("Cache instances require an ID.");
if (this == o)
return true;
if (!(o instanceof Cache))
return false;
Cache otherCache = (Cache) o;
return getId().equals(otherCache.getId());
}
@Override
public int hashCode() {
if (getId() == null)
throw new CacheException("Cache instances require an ID.");
return getId().hashCode();
}
}
5)配置标签
在需要缓冲的映射文件中加入<cache/>标签,并且指定提供缓存功能的cache实现类的全限定名
<cache type="com.briup.cache.MybatisRedisCache"></cache>