mybatis 解决join语句缓存刷新研究

项目中由于需要从ibatis升级到mybatis,因为实现的改变,缓存功能也相应的改变,由于需要实现一个当前mybatis没提供的缓存功能,花了些时间研究了源码,并且实现了相应的功能,现就一些心得与大家分享,由于实现中使用了mybatis的plugin拦截器,有可能会改变mybatis的核心行为,所以不保证我的方法足够的安全,只是一个解决问题的思路,言归正传:
在mybatis下每个mapper的namespace对应一个cache, 也就是说一个cahce的id就是mapper的namespace, 当mapper中select 标签中使用useCache=true,那么该select语句就会被保存到cache中,某一个namespace下的某一个select语句可能会有不同的参数值,所以mybatis会分别把不同参值的sql查询结果保存到cache中去,也就是说同一个namespace下的同一个select语句会对应N个不同的cache, 当前mybatis的缓存flush机制是得到namespace对应的缓存后直接clear, 这个的话,同一个namespace下的所有select语句所对应的缓存都被刷新,这一点与ibatis一样,只要cacheModel声明过的select语句就会被flush,我们如何能做到细粒度的flush某个select呢? 或者是当namespace A 中的SQL语句要join 另一个namespace B中的表(B表),比如: namespace A中有这样一个SQL,当B表作了update操作的时候,那么SQL语句 getInfo所对应的缓存就需要flush, 但是当前mybatis没有提供这个功能,也或许我不知道怎么使用这个功能(如果有人知道麻烦赐教)
<select id="getInfo" useCache=true>
select A.name, B.detail from A left join B.id = A.id
</select>

为了解决这个问题,我使用了mybatis的plugin功能,首先拦截Executor class的query方法来得到以下三个参数MappedStatement.class, Object.class, RowBounds.class, 这个三个参数是为了计算存放到cahce中的key,然后再由Executor.createCacheKey(mappedStatement, parameter, rowBounds)方法计算出cacheKey, 这样就可以得到每个select语句被缓存到cahce中时所对应的key, 顺带说一下这个cacheKey的计算是由几个要素来计算的,1.select标签的id, 可通过MappedStatement.getId得到 2. RowBounds 的getOffset()和getLimit() 3. select的sql语句 4. 最重要的一点,也是决定这key是否相同的一点, sql的参数,由上面三个参数中的第二个提供, 当然cahceKey的不同也可能会由RowBounds的不同而不同。
得到cahceKey之后把它保存到一个Map<String, Set<CacheKey>>类型的map里,String对应一个sqlid, 比如上面提到的sql语句 getInfo, 不过还要加上namesapace那就是 A.getInfo, Set<CacheKey> 保存某个SQL所对应的不同查询参数的不同结果。当我们得到想要flush的select 的cachekey之后,就可以拦腰Executor class的update方法(包括insert,update,delete), 至于过程很简单,上源码。

在sqlMapConfig.xml中加上:
<plugins>
<plugin interceptor="com.nexaweb.bankcore.interceptor.FlushCacheInterceptor">
<property name="ClientGroup.getClientGroupByClientId" value="Client"/>
</plugin>

实现Interceptor接口:

@Intercepts( {
@Signature(type = Executor.class, method = "update", args = {
MappedStatement.class, Object.class }),
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class }) })
public class FlushCacheInterceptor implements Interceptor {

private String property;

private Properties properties;

private Map<String, Set<CacheKey>> keyMap = new HashMap<String, Set<CacheKey>>();

public Object intercept(Invocation invocation) throws Throwable {

MappedStatement mappedStatement = (MappedStatement) invocation
.getArgs()[0];

if (!mappedStatement.getConfiguration().isCacheEnabled())
return invocation.proceed();

String sqlId = mappedStatement.getId();
String nameSpace = sqlId.substring(0, sqlId.indexOf('.'));
Executor exe = (Executor) invocation.getTarget();
String methodName = invocation.getMethod().getName();
if (methodName.equals("query")) {
for (Object key : properties.keySet()) {
if (key.equals(sqlId)) {
Object parameter = invocation.getArgs()[1];
RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];
Cache cache = mappedStatement.getConfiguration().getCache(nameSpace);
cache.getReadWriteLock().readLock().lock();
CacheKey cacheKey = exe.createCacheKey(mappedStatement, parameter, rowBounds);
try {
if (cache.getObject(cacheKey) == null) {
if (keyMap.get(sqlId) == null) {
Set<CacheKey> cacheSet = new HashSet<CacheKey>();
cacheSet.add(cacheKey);
keyMap.put(sqlId, cacheSet);
} else {
keyMap.get(sqlId).add(cacheKey);
}
}
} finally {
cache.getReadWriteLock().readLock().unlock();
}
break;
}
}
} else if (methodName.equals("update")) {
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
String cacheSqlId = (String) e.nextElement();
String updateNameSpace = properties.getProperty(cacheSqlId);
if (updateNameSpace.equals(nameSpace)) {
String cacheNamespace = cacheSqlId.substring(0, cacheSqlId.indexOf('.'));
Cache cache = mappedStatement.getConfiguration().getCache(cacheNamespace);
Set<CacheKey> cacheSet = keyMap.get(cacheSqlId);
cache.getReadWriteLock().writeLock().lock();
try {
for (Iterator it = cacheSet.iterator(); it.hasNext();) {
cache.removeObject(it.next());
}
} finally {
cache.getReadWriteLock().writeLock().unlock();
keyMap.remove(cacheSqlId);
}

}
}
}

return invocation.proceed();
}

public Object plugin(Object target) {
return Plugin.wrap(target, this);
}

public void setProperties(Properties properties) {
this.properties = properties;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用MyBatis实现三表联合查询可以通过编写SQL语句来实现。首先,在Mapper文件定义一个查询语句,使用JOIN语句将三个表连接起来,并指定连接条件。然后,在Java代码调用该查询语句,将结果映射到对应的实体类。 以下是一个示例的Mapper文件配置: ```xml <!-- 定义查询语句 --> <select id="getThreeTableData" resultMap="resultMap"> SELECT t1.*, t2.*, t3.* FROM table1 t1 JOIN table2 t2 ON t1.id = t2.table1_id JOIN table3 t3 ON t2.id = t3.table2_id WHERE t1.id = #{id} </select> <!-- 定义结果映射 --> <resultMap id="resultMap" type="com.example.entity.ThreeTableEntity"> <!-- 定义字段映射 --> <result property="field1" column="t1_field1"/> <result property="field2" column="t1_field2"/> <!-- 省略其他字段映射 --> <association property="table2" javaType="com.example.entity.Table2Entity"> <result property="field3" column="t2_field3"/> <!-- 省略其他字段映射 --> <association property="table3" javaType="com.example.entity.Table3Entity"> <result property="field4" column="t3_field4"/> <!-- 省略其他字段映射 --> </association> </association> </resultMap> ``` 在Java代码调用该查询语句: ```java public ThreeTableEntity getThreeTableData(int id) { return sqlSession.selectOne("com.example.mapper.ThreeTableMapper.getThreeTableData", id); } ``` 关于MyBatis的一级缓存和二级缓存的配置,一级缓存是默认开启的,它是指在同一个SqlSession,对于相同的查询语句和参数,MyBatis会将查询结果缓存起来,下次再执行相同的查询时,直接从缓存获取结果,提高查询性能。 而二级缓存是在多个SqlSession之间共享的缓存,需要手动进行配置。可以在MyBatis的配置文件添加以下配置: ```xml <!-- 开启二级缓存 --> <settings> <setting name="cacheEnabled" value="true"/> </settings> <!-- 配置二级缓存 --> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> ``` 需要注意的是,使用二级缓存时,需要确保查询的结果是可序列化的,并且实体类需要实现Serializable接口。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值