spring boot + mybatis plus 二级缓存配置方式
Spring boot
pom.xml 关键配置
<!-- spring boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.19.RELEASE</version>
<relativePath/>
</parent>
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
关键代码
dao
//使用注解方式开启二级缓存
@CacheNamespace(implementation = MybatisCache.class)
public interface TestDao extends BaseMapper<Test> {
@Select("SELECT * from test,test2 where test.id = test2.f_id and test.id = #{id}")
//不使用缓存
@Options(useCache = false)
Test getById(String id);
//默认使用缓存
@Select("select * from test where id = #{id}")
Test getById(List<String> ids);
int update(String id)
}
mapper.xml
mapper 使用缓存的方式是使用”<cache-ref>“标签引用dao的命名空间,因为dao中已经开启缓存,
这样与dao中的缓存保持一直,如果mapper文件不引用缓存,
执行update方法时,不会清除dao的缓存,导致数据库数据与缓存数据不一致。
如果直接使用”<cache>“标签开启缓存,会与dao中的冲突,服务启动失败。
<mapper namespace="com.seentao.dmc.student.dao.StuClassTrainingDao">
<!-- 缓存开启方式使用”<cache-ref>“标签引用dao中的缓存 -->
<cache-ref namespace="com.seentao.dmc.student.dao.StuClassTrainingDao"/>
<!-- 假设有些复杂的sql语句,dao中不支持,可在mapper文件中写 -->
<update id="upldate" parameterType="java.util.List">
update test
set name = 'xxx'
where id in
<foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</update>
</mapper>
工作中遇到的执行mapper文件中的SQL语句缓存没有清除的问题,在此记录一下,个人见解,如有错误请指正。