1. 程式人生 > >mybatis的快取問題

mybatis的快取問題

1) 一級快取
   每個sqlsession都有一個一級快取,只要sql語句和引數相同,只有第一次查詢資料庫,並且會把查詢結果放入一級快取之後的查詢,就直接從一級快取中獲取結果。
   
   一級快取的作用範圍,只限於一個sqlsession

    @Test
    public void test2() {
        SqlSession s1 = factory.openSession();
        s1.selectOne("com.westos.mapper.ProductMapper.select1", 1);
        System.out.println("======================");
        s1.selectOne("com.westos.mapper.ProductMapper.select1", 1);
        s1.close();
    }

   
2) 二級快取
所有sqlSession共享的快取,一級快取無需配置,而二級快取需要配置,二級快取的意義是減少與資料庫的互動,從而提升程式的效能(SqlMapConfig.xml修改)

<settingname='cacheEnabled'value='true'/>

    <settings>

       <!-- 開啟二級快取 預設值為true -->

    <settingname='cacheEnabled'value='true'/>

    </settings>

    @Test
    public void test2() {
        SqlSession s1 = factory.openSession();
        s1.selectOne("com.westos.mapper.ProductMapper.select1", 1); 
        s1.close();
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        SqlSession s2 = factory.openSession();
        s2.selectOne("com.westos.mapper.ProductMapper.select1", 1);
        s2.close();
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        SqlSession s3 = factory.openSession();
        Product product  = new Product();
        product.setId(1);
        product.setName("TCL 55A950C 55英寸32核人工智慧 HDR曲面超薄4K電視金屬機身(槍色)");
        product.setTablename("abc");
        product.setPrice(2499.00);
        s3.update("com.westos.mapper.ProductMapper.update", product);
        s3.commit();
        s3.close();
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        SqlSession s4 = factory.openSession();
        s4.selectOne("com.westos.mapper.ProductMapper.select1", 1); 
        s4.close();
       
    }

3) 快取失效
只要是執行了增,刪,改的操作,快取就應該失效,仍然從資料庫查詢得到最新結果

4) 二級快取適用場景
當資料的查詢遠遠多於修改時, 才有啟用二級快取的必要