最近研究标志映射,提到了最理想的保存标识映射的地方时工作单元,其次是会话。联想到mybatis的sqlsession。于是做了一个测试,在一个事务方法中不断调用mapper的查询方法,观察日志打印,看究竟查询了几次数据库。
这里给MappedStatement的构建者set
日志输出如下:
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