Mybaits 提供一级缓存(SqlSession 局部缓 每个session之间相互不影响)和二级缓存是Mapper级别的是跨Sqlsession的(多个Sqlsession公用一个缓存区域)。一级缓存默认是开启的,二级缓存默认是不开启的。
Mybaits使用一级和二级缓存基于 PerpetualCache的 HashMap 本地缓存,然而mybatis提供Cache接口可以很方便的让我们去整合一些分布式缓存如ehcache、Redis等,只要实现Cache接口进行开发即可。
public interface Cache {
/**
* @return The identifier of this cache
*/
String getId();
/**
* @param key Can be any object but usually it is a {@link CacheKey}
* @param value The result of a select.
*/
void putObject(Object key, Object value);
/**
* @param key The key
* @return The object stored in the cache.
*/
Object getObject(Object key);
/**
* Optional. It is not called by the core.
*
* @param key The key
* @return The object that was removed
*/
Object removeObject(Object key);
/**
* Clears this cache instance
*/
void clear();
/**
* Optional. This method is not called by the core.
*
* @return The number of elements stored in the cache (not its capacity).
*/
int getSize();
/**
* Optional. As of 3.2.6 this method is no longer called by the core.
*
* Any locking needed by the cache must be provided internally by the cache provider.
*
* @return A ReadWriteLock
*/
ReadWriteLock getReadWriteLock();
}
Mybaits 本地缓存
public class PerpetualCache implements Cache {
private String id;
private Map<Object, Object> cache = new HashMap<Object, Object>();
public PerpetualCache(String id) {
this.id = id;
}
public String getId() {
return id;
}
public int getSize() {
return cache.size();
}
public void putObject(Object key, Object value) {
cache.put(key, value);
}
public Object getObject(Object key) {
return cache.get(key);
}
public Object removeObject(Object key) {
return cache.remove(key);
}
public void clear() {
cache.clear();
}
public ReadWriteLock getReadWriteLock() {
return null;
}
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());
}
public int hashCode() {
if (getId() == null) throw new CacheException("Cache instances require an ID.");
return getId().hashCode();
}
}
一级缓存原理:sqlSession 关闭或者执行commit操作 一级缓存就会被清空。
二级缓存原理:二级缓存与一级缓存区别,二级缓存的范围更大,多个sqlSession可以共享一个Mapper的二级缓存区域。每一个namespace 的Mapper 都有一个独立缓存区域。
mybaits 缓存局限:mybatis二级缓存对细粒度的数据级别的缓存实现不好,当数据库数据中一条记录发生改变的时候,就会清空缓存,无法做到只清空该记录的缓存。
配置文件配置:
<settings> <setting name="cacheEnabled" value="true"/> </settings>
mapper命名空间配置
<mapper namespace="com.hsc.Mapper.TestMapper"> <cache/>