mybatis缓存

一级缓存:

mybatis默认是开启,有效范围是同一个sqlsession对象

第一次查询完成后,结果会存到缓存中,第二次相同语句的查询,就会在缓存中找,而不走数据库查询

但是:在执行增加 删除 修改操作后会清空缓存(事务提交)

二级缓存:

需要手动开启

1,在配置文件中开启缓存(默认开启,可不管)

<setting name="cacheEnabled"value="true"/>

2,sql映射文件中,添加<cache标签

<cache eviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>

3,查询对象类实现序列化接口(保证安全,查询结果序列化到缓存中)

注意点:测试二级缓存需要使用同一个sqlsessionfactory对象,单例模式可以搞一个util类

测试代码:

@Test
    public void selectUserParam1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sessionFactory.openSession(true);
        SqlSession sqlSession1 = sessionFactory.openSession(true);
        StuMapper2 mapper = sqlSession.getMapper(StuMapper2.class);
        long l = System.currentTimeMillis();
        User zs = mapper.selectUserParam(2, "zs");
        long l1 = System.currentTimeMillis();
        System.out.println(l1-l+"毫秒");
        sqlSession.close();

        StuMapper2 mapper1 = sqlSession1.getMapper(StuMapper2.class);
        long ll = System.currentTimeMillis();
        User zsl = mapper1.selectUserParam(2, "zs");
        long l1l = System.currentTimeMillis();
        System.out.println(ll-l1l+"毫秒");
        sqlSession1.close();
    }

结果

182c81c7e8ff481f8bde347c2a034b48.png

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值