MyBatis注解 @CacheNamespace的用法解析
本文更新日期:2019年10月5日
1、@CacheNamespace的源码分析
@CacheNamespace注解主要用于mybatis二级缓存,等同于<cache>属性。默认情况下,MyBatis 3 没有开启二级缓存,要开启二级缓存,需要在SQL 映射文件(mapper.xml)中添加一行:
<mapper namespace="cn.mybatis.mydemo.mapper.StudentMapper">
   <cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"></cache>
</mapper>当然,前提还需要在全局配置文件中开启缓存:
<setting name="cacheEnabled" value="true"/>CacheNamespace是注解,其源码如下所示:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CacheNamespace {
  Class<? extends org.apache.ibatis.cache.Cache> implementation() default PerpetualCache.class;
  Class<? extends org.apache.ibatis.cache.Cache> eviction() default LruCache.class;
  long flushInterval() default 0;
  int size() default 1024;
  boolean readWrite() default true;
  
  boolean blocking() default false;
  Property[] properties() default {};
}
2、CacheNamespace的使用注意事项
虽然xml配置和注解的功能基本相同,但是使用@CacheNamespace时候要注意:配置文件和接口注释是不能够配合使用的。只能通过全注解的方式或者全部通过xml配置文件的方式使用。见下面的例子:
@CacheNamespace(implementation = MybatisRedisCache.class)
public interface UserMapper(
    @Select("select * from t_user where user_id = #{userId}")
    @Options(useCache = true)
    List<User> getUser(User u);
}<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.UserMapper">
 
    <cache type="cn.mybatis.MybatisRedisCache">
        <property name="eviction" value="LRU" />
        <property name="flushInterval" value="6000000" />
        <property name="size" value="1024" />
        <property name="readOnly" value="false" />
    </cache>
 
    <select id="selectById">
        select * from test where id = #{id}
    </select >
</mapper>