Mybatis学习第13节 -- 缓存-mybatis的一级缓存

测试

@Test
public void testCacheLevelOne() {
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.println(mapper.getShopById(1));
System.out.println(mapper.getShopById(1));

session.close();
}

结果

2018-12-28 16:21:13,332 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Preparing: select * from tb_shop where `shop_id` = ? 
2018-12-28 16:21:13,403 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Parameters: 1(Integer)
2018-12-28 16:21:13,491 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - <== Total: 1
Shop{id=1, ownerId=1, areaId=3, categoryId=14, name='正式店铺名称', desc='测试描述', addr='正式地址', phone='13810524086', image='/upload/item/shop/1/2017091621545314507.jpg', priority=10, createTime=2017-08-03, lastEditTime=2017-09-16, enableStatus=0, advice='审核中'}

Shop{id=1, ownerId=1, areaId=3, categoryId=14, name='正式店铺名称', desc='测试描述', addr='正式地址', phone='13810524086', image='/upload/item/shop/1/2017091621545314507.jpg', priority=10, createTime=2017-08-03, lastEditTime=2017-09-16, enableStatus=0, advice='审核中'}

再次测试

@Test
public void testCacheLevelOne() {
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.println(mapper.getShopById(1));
session.close();

session = MyBatisUtil.getSqlSession();
mapper = session.getMapper(ShopMapper.class);
System.out.println(mapper.getShopById(1));
session.close();
}

再次测试的结果

2018-12-28 16:32:39,882 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Preparing: select * from tb_shop where `shop_id` = ? 
2018-12-28 16:32:39,981 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Parameters: 1(Integer)
2018-12-28 16:32:40,052 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - <== Total: 1
Shop{id=1, ownerId=1, areaId=3, categoryId=14, name='正式店铺名称', desc='测试描述', addr='正式地址', phone='13810524086', image='/upload/item/shop/1/2017091621545314507.jpg', priority=10, createTime=2017-08-03, lastEditTime=2017-09-16, enableStatus=0, advice='审核中'}

2018-12-28 16:32:40,055 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Preparing: select * from tb_shop where `shop_id` = ? 
2018-12-28 16:32:40,055 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - ==> Parameters: 1(Integer)
2018-12-28 16:32:40,059 [main] DEBUG [io.github.coinsjack.dao.ShopMapper.getShopById] - <== Total: 1
Shop{id=1, ownerId=1, areaId=3, categoryId=14, name='正式店铺名称', desc='测试描述', addr='正式地址', phone='13810524086', image='/upload/item/shop/1/2017091621545314507.jpg', priority=10, createTime=2017-08-03, lastEditTime=2017-09-16, enableStatus=0, advice='审核中'}

总结

可以看到,在同一个session中, 对于同一个查询执行两次, 实际上只执行了一次, 把session关闭之后再次进行查询, 发现有重新去数据库查询了一遍,所以一级缓存生存于session中
posted @ 2019-03-17 10:45  不怕旅途多坎坷  阅读(124)  评论(0编辑  收藏  举报