Tuesday 8 July 2014

Remove a single entry from a MyBatis cache programatically

MyBatis automatically flushes its cache on a insert/update/delete statement. But what if you need to flush a item from the cache because its database representation has been changed by a different application? Here is how to remove a single entry from a MyBatis cache programatically:


public Object removeCacheEntry(SqlSession sqlSession, String cacheId, String mappingName, Object parameterObject) {
    Object removedObject = null;
    Cache cache = getCache(sqlSession, cacheId);
    if (cache != null) {
        CacheKey cacheKey = getCacheKey(sqlSession, mappingName, parameterObject);
        if (cacheKey != null) {
            removedObject = cache.removeObject(cacheKey);
            logger.info("Remove from cache: {} by key {}", removedObject, cacheKey);
        }
    }
    return removedObject;
}

private Cache getCache(SqlSession sqlSession, String cacheId) {
    return sqlSession.getConfiguration().getCache(cacheId);
}

private CacheKey getCacheKey(SqlSession sqlSession, String mappingName, Object parameterObject) {
    Configuration configuration = sqlSession.getConfiguration();
    SimpleExecutor executor = new SimpleExecutor(configuration, null);
    MappedStatement mappedStatement = configuration.getMappedStatement(mappingName);
    BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
    return executor.createCacheKey(mappedStatement, parameterObject, RowBounds.DEFAULT, boundSql);
}

For example:


removeCacheEntry(qlSession, "com.test.MyEntityMapper", "com.test.MyEntityMapper.getById", 1);

No comments:

Post a Comment