SpringBoot开启Mybatis二级缓存

  • A+
所属分类:mybatis SpringBoot

大家知道,Mybatis默认二级缓存是关闭的,如果我们想打开二级缓存,只需要2步。

1.在application.properties中加上以下配置

mybatis.configuration.cache-enabled=true

2.在mapper的xml文件中的namespace中加上

<cache></cache>

即可。直接这样执行sql会报错,因为开启了二级缓存后entity类必须要序列化序列化后就可以正常使用了。

这里需要注意的是,同样的sql多次执行中控制台还是会显示sql语句,但是这并不是说发了2次sql,因为如果缓存生效了,控制台里会提示Cache Hit xxx,就表明是从缓存中取得的结果了。例如:

 2020-06-10 11:22:08.469 DEBUG 2012 --- [ main] c.e.m.mapper.UserMapper : Cache Hit Ratio [com.example.myspringbootmybaitsxml.mapper.UserMapper]: 0.0
2020-06-10 11:22:08.474 INFO 2012 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-06-10 11:22:08.598 INFO 2012 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-06-10 11:22:08.604 DEBUG 2012 --- [ main] c.e.m.m.UserMapper.getUserByCondition : ==> Preparing: select user_id, user_name, nick_name, sex, address from user WHERE user_id in ( ? , ? ) and user_name like concat('%',?, '%')
2020-06-10 11:22:08.623 DEBUG 2012 --- [ main] c.e.m.m.UserMapper.getUserByCondition : ==> Parameters: 1(Integer), 2(Integer), 1(String)
2020-06-10 11:22:08.639 DEBUG 2012 --- [ main] c.e.m.m.UserMapper.getUserByCondition : <== Total: 2
[User(userId=1, userName=11, nickName=111, sex=1, address=11, dep=null), User(userId=2, userName=11, nickName=111, sex=0, address=22, dep=null)]
ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: