使用场景
一级缓存
订单表与会员表是存在一对多的关系 为了尽可能减少join 查询,进行了分阶段查询,即先查询出订单表,在根据member_id 字段查询出会员表,最后进行数据整合 。如果订单表中存在重复的member_id,就会出现很多没必要的重复查询。
针对这种情况myBatis 通过1缓存来实现,在同一次查询会话中如果出现相同的语句及参数,就会从缓存中取出不在走数据库查询。1级缓存只能作用于查询会话中 所以也叫做会话缓存。
一级缓存的使用条件:
1.必须是相同的SQL和参数
2.必须是相同的会话
3.必须是相同的namespace 即同一个mapper
4.必须是相同的statement 即同一个mapper 接口中的同一个方法
5.查询语句中间没有执行session.clearCache() 方法
6.查询语句中间没有执行 insert update delete 方法(无论变动记录是否与 缓存数据有无关系)
一级缓存获取
1.org.apache.ibatis.session.defaults.DefaultSqlSession#selectList()
2.org.apache.ibatis.executor.BaseExecutor#query()
3.org.apache.ibatis.cache.impl.PerpetualCache#getObject
一级缓存存储
1.org.apache.ibatis.session.defaults.DefaultSqlSession#selectList()
2.org.apache.ibatis.executor.BaseExecutor#query()
3.org.apache.ibatis.cache.impl.PerpetualCache#getObject
4.org.apache.ibatis.executor.BaseExecutor#queryFromDatabase
5.org.apache.ibatis.cache.impl.PerpetualCache#putObject
缓存的清除
1.org.apache.ibatis.session.defaults.DefaultSqlSession#clearCache
2.org.apache.ibatis.executor.BaseExecutor#clearLocalCache
3.org.apache.ibatis.executor.BaseExecutor#clearLocalCache
4.org.apache.ibatis.cache.impl.PerpetualCache#clear
二级缓存
业务系统中存在很多的静态数据如,字典表、菜单表、权限表等,这些数据的特性是不会轻易修改但又是查询的热点数据。一级缓存针对的是同一个会话当中相同SQL,并不适合这情热点数据的缓存场景。为了解决这个问题引入了二级缓存,它脱离于会话之外。
二级缓存使用条件:
1.当会话提交或关闭之后才会填充二级缓存
2.必须是在同一个命名空间之下
3.必须是相同的statement 即同一个mapper 接口中的同一个方法
4.必须是相同的SQL语句和参数
5.如果readWrite=true ,实体对像必须实现Serializable 接口
二级缓存清除条件:
1.xml中配置的update 不能清空 @CacheNamespace 中的缓存数据
2.只有修改会话提交之后 才会执行清空操作
3.任何一种增删改操作 都会清空整个namespace 中的缓存
缓存获取(这里使用的是装饰者模式)
>org.apache.ibatis.cache.TransactionalCacheManager#getObject
>org.apache.ibatis.cache.decorators.TransactionalCache#getObject
>org.apache.ibatis.cache.decorators.SynchronizedCache#getObject
>org.apache.ibatis.cache.decorators.LoggingCache#getObject
>org.apache.ibatis.cache.decorators.SerializedCache#getObject
>org.apache.ibatis.cache.decorators.ScheduledCache#getObject
>org.apache.ibatis.cache.decorators.LruCache#getObject
>org.apache.ibatis.cache.impl.PerpetualCache#getObject
保存二级缓存
org.apache.ibatis.executor.CachingExecutor#close
>org.apache.ibatis.cache.TransactionalCacheManager#commit
>org.apache.ibatis.cache.decorators.TransactionalCache#flushPendingEntries
>org.apache.ibatis.cache.decorators.SynchronizedCache#putObject
>org.apache.ibatis.cache.decorators.LoggingCache#putObject
>org.apache.ibatis.cache.decorators.SerializedCache#putObject
>org.apache.ibatis.cache.decorators.ScheduledCache#putObject
>org.apache.ibatis.cache.decorators.LruCache#putObject
>org.apache.ibatis.cache.impl.PerpetualCache#putObject
缓存清除
1.org.apache.ibatis.session.defaults.DefaultSqlSession#selectList()
2.org.apache.ibatis.executor.CachingExecutor#query()
3.org.apache.ibatis.executor.CachingExecutor#flushCacheIfRequired