Clear MyBatis First-Level Cache in Spring

After integrating MyBatis into Spring, the first-level cache is automatically enabled and cannot be manually disabled. The first-level cache is a cache that operates within the same SqlSession, it can improve query performance but may also lead to data inconsistency issues.

If you want to remove data from the first-level cache, you can use the clearCache() method of SqlSession to clear the cache. For example:

@Autowired
private SqlSessionFactory sqlSessionFactory;

public void clearCache() {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
        sqlSession.clearCache();
    }
}

Simply call the clearCache() method where you need to clear the cache.

Additionally, if you want to automatically clear the cache after each query, you can configure the ‘localCacheScope’ in the MyBatis configuration file to be ‘STATEMENT’. This will clear the first-level cache after each query. For example:

<configuration>
    <settings>
        <setting name="localCacheScope" value="STATEMENT"/>
    </settings>
</configuration>

It should be noted that disabling the first-level cache may lead to a decrease in query performance, so in most cases, it is more appropriate to keep the first-level cache enabled.

bannerAds