参考
https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache
说明
Spring 整合 MyBatis 时一级缓存失效问题
- 在未开启事务的情况之下,每次查询,spring 都会关闭旧的 sqlSession 而创建新的 sqlSession, 因此此时的一级缓存是没有启作用的
- 在开启事务的情况之下,spring 使用 threadLocal 获取当前资源绑定同一个 sqlSession,因此此时一级缓存是有效的
当开启缓存后,数据的查询执行的流程就是 二级缓存 -> 一级缓存 -> 数据库
spring整合 mybatis 中,一级缓存失效及带来脏数据,应该使用STATEMENT
级别缓存
示例:会话1 获取数据,会话 2 修改数据。会话 1 再次获取,返回缓存数据,与实际数据不一致
对于频繁变动的数据,没必要缓存。对于变化较慢但经常访问的数据,建议缓存
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true"/> <setting name="localCacheScope" value="STATEMENT"/> </settings> </configuration>
|
spring-mybatis.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="plugins"> <array> <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties" value="reasonable=false"></property> </bean> </array> </property> <property name="mapperLocations" value="classpath:mapping/*.xml" />
<property name="configLocation" value="classpath:mybatis-config.xml" /> </bean>
|
XXXDao.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <mapper namespace="com.bjtcrj.gms.infos.persistence.dao.PersonDao" > <cache/> </mapper>
<select ... flushCache="false" useCache="true"/> <insert ... flushCache="true"/> <update ... flushCache="true"/> <delete ... flushCache="true"/>
<select id="XXXX" flushCache="true">
|
XXX.java
1 2 3 4 5
| public class Person implements Serializable { private static final long serialVersionUID = 2191308980208745706L; }
|