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