二级缓存作用域在Mapper中。当一级缓存失效后,一级缓存中的数据会转移到二级缓存中
1.在Mybatis中开启二级缓存
| <setting name="cacheEnabled" value="true"/> |
2.在Mapper.xml中
3.测试
| public void getUserById (){ |
| SqlSession sqlSession = sqlSessionFactory.getsqlSession(); |
| |
| userMapper mapper = sqlSession.getMapper(userMapper.class); |
| |
| |
| user user1 = mapper.getUserById(2); |
| System.out.println(user1); |
| sqlSession.close(); |
| System.out.println("========="); |
| SqlSession sqlSession1 = sqlSessionFactory.getsqlSession(); |
| |
| userMapper mapper1 = sqlSession1.getMapper(userMapper.class); |
| user user2 = mapper1.getUserById(2); |
| System.out.println(user2); |
| sqlSession1.close(); |
| |
| } |
4.结果
| Caused by: java.io.NotSerializableException: com.Google.pojo.user |
解决方法
在实体类中继承序列化
| public class user implements Serializable { |
| private int id; |
| private String name; |
| private String pwd; |
| } |
结果
| Opening JDBC Connection |
| Created connection 1304589447. |
| Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487] |
| ==> Preparing: select * from user where id=? |
| ==> Parameters: 2(Integer) |
| <== Columns: id, name, pwd |
| <== Row: 2, aaa, bbb |
| <== Total: 1 |
| user(id=2, name=aaa, pwd=bbb) |
| Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487] |
| Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4dc27487] |
| Returned connection 1304589447 to pool. |
| ========= |
| Cache Hit Ratio [com.Google.mapper.userMapper]: 0.5 |
| user(id=2, name=aaa, pwd=bbb) |
这里可以看到,第一个sqlSession关闭后,缓存给了二级缓存,然后第二个sqlSession直接得到了来自缓存中的数据。这就是二级缓存(补充了一级缓存的缺点)
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术