SoFunction
Updated on 2025-05-15

A brief analysis of how SpringBoot integrates Mybatis to achieve secondary cache

mybatis native

Level 2 cache refers to sharing data between multiple Sqlsessions, but caches such as Redis can also be used as storage points. But the method in mybatisplus is not supported.

Processing class, used to intercept mapper cache.

import ;
public record MybatisRedisCache(String id) implements Cache {

    private static final StringRedisTemplate redisTemplate;

    static {
        redisTemplate = ();
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (value != null) {
            ().set(getKey(key), (value));
        }
    }

    @Override
    public Object getObject(Object key) {
        String string = ().get(getKey(key));
        if (string == null) return null;
        return isArray(string);
    }

    @Override
    public Object removeObject(Object key) {
        String redisKey = getKey(key);
        Object value = ().get(redisKey);
        (redisKey);
        return value;
    }

    @Override
    public void clear() {
        (((getKey("*"))));
    }

    @Override
    public int getSize() {
        return 0;
    }

    private String getKey(Object key) {
        return id + ":" + ();
    }

    public Object isArray(String str) {
        JSON json = (str);
        if (json instanceof ) {
            // is an array            return (() json, );
        }
        if (json instanceof ) {
            // is an object            return (() json, );
        }
        throw new RuntimeException("Error in cache data format");
    }

}

mapper xml

You must add cache-ref to perform secondary cache

<mapper namespace="">

    <cache-ref namespace=""/>

    <select  resultType="">
        select *
        from demo
    </select>
</mapper>

Just configure CacheNamespace to use

@CacheNamespace(implementation = )
public interface UserMapper extends BaseMapper<Demo> {

    List<Demo> selectAll();

}

Spring Cache

@Configuration
@EnableCaching
public class RedisCacheConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = ()
                .entryTtl((10)) // Default cache 10 minutes                .disableCachingNullValues() // Avoid storage control                .serializeValuesWith( // Set Serialization                        (new GenericJackson2JsonRedisSerializer())
                );
        // return        return (factory).cacheDefaults(config).build();
    }

}

Cacheable cache, CacheEvict delete, splicing key

@Service
public class DemoService extends ServiceImpl&lt;UserMapper, Demo&gt; {

    @Cacheable(value = "user:cache", key = "#id")
    public Demo getOne(Long id) {
        return getById(id);
    }


    @Caching(evict = {
            @CacheEvict(value = "user:cache", key = "#id"),
            @CacheEvict(value = "user:all", allEntries = true)}
    )
    public void deleteById(String id) {
        removeById(id);
    }

    // Refresh the cache after updating the data    @Caching(
            put = {@CachePut(value = "user:cache", key = "#", unless = "#result == null")},
            evict = {@CacheEvict(value = "user:all", allEntries = true)}
    )
    public void updateUser(Demo demo) {
        updateById(demo);
    }

    @Cacheable(value = "user:all")
    public List&lt;Demo&gt; listDemo() {
        return list();
    }

}

This is the article about this brief analysis of how SpringBoot integrates Mybatis to achieve secondary cache. For more related SpringBoot Mybatis content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!