🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 二级缓存概念 MyBatis中SqlSessionFactory缓存.由同一个SqlSessionFactory对象创建的SqlSessionFactory共享其缓存. ## 配置 让MyBatis框架支持二级缓存(MyBatis配置文件): ~~~ <settings> <setting name="cacheEnabled" value="true"/> //默认就是true </settings> ~~~ 让当前的映射文件支持二级缓存(XML配置文件): ~~~ <mapper namespace="com.like.dao.IUserDao"> <cache/> //设置此标签 <select id="findById" parameterType="int" resultType="com.like.domain.User" useCache="true"> select * from user where id = #{id} </select> </mapper> ~~~ 让当前的操作支持二级缓存(在select标签配置): ~~~ <mapper namespace="com.like.dao.IUserDao"> <cache/> <select id="findById" parameterType="int" resultType="com.like.domain.User" useCache="true"> //useCache设为true select * from user where id = #{id} </select> </mapper> ~~~ ## 代码 ~~~ IUserDao mapper1 = session1.getMapper(IUserDao.class); User user1 = mapper1.findById(41); session1.close(); IUserDao mapper2 = session2.getMapper(IUserDao.class); User user2 = mapper2.findById(41); System.out.println(user1 == user2); //这里是false,这里存放的是数据,不是对象 ~~~ ``` 2019-04-04 21:19:33,204 0 [ main] DEBUG ache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter. 2019-04-04 21:19:33,420 216 [ main] DEBUG com.like.dao.IUserDao - Cache Hit Ratio [com.like.dao.IUserDao]: 0.0 2019-04-04 21:19:33,426 222 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection 2019-04-04 21:19:33,672 468 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@569cfc36] 2019-04-04 21:19:33,682 478 [ main] DEBUG com.like.dao.IUserDao.findById - ==> Preparing: select * from user where id = ? //只查询了这一次 2019-04-04 21:19:33,723 519 [ main] DEBUG com.like.dao.IUserDao.findById - ==> Parameters: 41(Integer) 2019-04-04 21:19:33,759 555 [ main] DEBUG com.like.dao.IUserDao.findById - <== Total: 1 User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', accounts=null} 2019-04-04 21:19:33,775 571 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@569cfc36] 2019-04-04 21:19:33,776 572 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@569cfc36] 2019-04-04 21:19:33,853 649 [ main] DEBUG com.like.dao.IUserDao - Cache Hit Ratio [com.like.dao.IUserDao]: 0.5 User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', accounts=null} false //这里是false ```