mybatis 高速缓存和二级缓存

本文详细探讨了MyBatis的一级缓存和二级缓存的工作原理。在事务过程中,数据首先存储在一级缓存,事务提交时,二级缓存才将数据真正保存。若在事务未提交时查询,二级缓存无法命中,只有在提交事务后才能从二级缓存获取数据。因此,理解事务与缓存的关系对于有效利用MyBatis的缓存功能至关重要。
摘要由CSDN通过智能技术生成
最近研究标志映射,提到了最理想的保存标识映射的地方时工作单元,其次是会话。联想到mybatis的sqlsession。于是做了一个测试,在一个事务方法中不断调用mapper的查询方法,观察日志打印,看究竟查询了几次数据库。

日志输出如下:

DEBUG - Cache Hit Ratio [com.demo.dao.PersonMapper]: 0.0
DEBUG - JDBC Connection [jdbc:mysql://localhost:3306/test, UserName=root@localhost, MySQL-AB JDBC Driver] will be managed by Spring
DEBUG - ==>  Preparing: select id, name, age from person where id = ? 
DEBUG - ==> Parameters: 15(Integer)
DEBUG - <==      Total: 1
DEBUG - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e63606]
DEBUG - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e63606] from current transaction
DEBUG - Cache Hit Ratio [com.demo.dao.PersonMapper]: 0.0
DEBUG - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e63606]
DEBUG - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e63606] from current transaction
DEBUG - Cache Hit Ratio [com.demo.dao.PersonMapper]: 0.0
DEBUG - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e63606]
sql语句打印一次,只查询了一次数据库,后面两次调用没有查询。session期间的确存在一个缓存将结果保存起来。


先看一下MappedStatement初始化。

MapperBuilderAssistant类负责MappedStatement初始化,其中有个setStatementCache代码中有这么一句:

statementBuilder.cache(cache);

这里给MappedStatement的构建者set
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值