更新時(shí)間:2023-04-20 來源:黑馬程序員 瀏覽量:
一級(jí)緩存
一級(jí)緩存基于PerpetualCache的HashMap本地緩存,其存儲(chǔ)作用域?yàn)镾ession,當(dāng)Session進(jìn)行flush或close之后,該Session中的所有Cache就將清空,默認(rèn)打開一級(jí)緩存。
//2.獲取SqlSession對(duì)象,用它來執(zhí)行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 執(zhí)行 sql //3.1 獲取UserMapper接口的代理對(duì)象 UserMapper userMapper1 = sqlSession.getMapper(UserMapper.class); UserMapper userMapper2 = sqlSession.getMapper(UserMapper.class); User user = userMapper1.selectById(6); System.out.println(user); System.out.println("---------------------"); User user1 = userMapper2.selectById(6); System.out.println(user1);
二級(jí)緩存
二級(jí)緩存是基于namespace和mappe的作用域起作用的,不是依賴于SQL session,默認(rèn)也是采用PerpetualCache,HashMap存儲(chǔ)
//2.獲取SqlSession對(duì)象,用它來執(zhí)行sql SqlSession sqlSession1 = sqlSessionFactory.openSession(); //3.執(zhí)行sql //3.1獲取 UserMapper接口的代理對(duì)象 UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class); User user1 = userMapper1.selectByld(6); System.out.println(user1); sqlSession1.close(); SqlSession sqlSession2 = sqlSessionFactory.openSession(); System.out.println("---------------------"); UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class); User user2 = userMapper2.selectByld(6); System.out.printin(user2); //4.關(guān)閉資源 sqlSession2.close();
當(dāng)某一個(gè)作用域(一級(jí)緩存Session/二級(jí)緩存Namespaces)的進(jìn)行了新增、修改、刪除操作后,默認(rèn)該作用域下所有select中的緩存將被clear。
注意事項(xiàng):1,對(duì)于緩存數(shù)據(jù)更新機(jī)制,當(dāng)某一個(gè)作用域(一級(jí)緩存Session/二級(jí)緩存Namespaces)的進(jìn)行了新增、修改、刪除操作后,默認(rèn)該作用域下所有select中的緩存將被clear2,二級(jí)緩存需要緩存的數(shù)據(jù)實(shí)現(xiàn)Serializable接口3,只有會(huì)話提交或者關(guān)閉以后,一級(jí)緩存中的數(shù)據(jù)才會(huì)轉(zhuǎn)移到二級(jí)緩存中。