Flush MyBatis Cache externally (outside of mapper)
Asked Answered
S

2

5

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.

Sweyn answered 13/1, 2016 at 14:27 Comment(0)
M
9

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();
        }
    }
Minos answered 14/1, 2016 at 7:2 Comment(2)
not helpful, the question was outside of mybatis mapperSweyn
I update the answer , you can do it by getting cache from configuration.Minos
F
0

Hi i have used another approach, because we used spring. Use autowire the Session implementation and call appropriate method

public class SomeServerClass{

    @Autowired
    private org.mybatis.spring.SqlSessionTemplate sqlSessionTemplate;

    private void someClearMethod(){
        sqlSessionTemplate.clearCache();
    }
}

If I use interface org.apache.ibatis.session.SqlSession it refers to same instance

Feed answered 3/2, 2016 at 9:8 Comment(1)
As the JavaDoc of SqlSessionTemplate.clearCache() states "Clears local session cache" I assume this clears the local (per thread) cache rather than the global session-independent cacheSweyn

© 2022 - 2024 — McMap. All rights reserved.