Search code examples
cachingmybatisspring-mybatis

Flush MyBatis Cache externally (outside of mapper)


I'm using MyBatis with second level cache activated via <cache/> in xml mapper files.

Suppose I want to interact with the underlying DB/DataSource decoupled from MyBatis, for instance via direct jdbcTemplate.

How can I assure, that the MyBatis cache gets flushed appropriateley when I Insert/Update/Delete via jdbcTemplate on a table for that MyBatis holds cached query results.

In other words, how can I force MyBatis to flush its cache from outside of MyBatis mappers for certain cache namespace?

I'm aware of @Options(flushCache=true) annotation, but this seems not to work outside of mapper interfaces.


Solution

  • you can get cache from configuration and then get by namespace and clear it.

        @Resource
        SqlSessionFactory sqlSessionFactory;
    
        public void clearCacheByNamespace(){
            Configuration config = sqlSessionFactory.getConfiguration();
            Cache cache = config.getCache("com.persia.dao.UserInfoMapper");
            if(cache != null){
                cache.clear();
            }
        }