用編程方式證明Hibernate中一級緩存的存在

寫一個查詢小例子

// 测试一级缓存的存在

    @Test

    public void demo8(){

        Session session = HibernateUtils.openSession();

        Transaction transaction = session.beginTransaction();

                                                                                     

        Book book = (Book) session.get(Book.class, "2c2882bc42f1e93b0142f1e93d2c0000");

        System.out.println(book);

        System.out.println("========================================================");

        // 再次执行同样的查询 -- 直接使用一级缓存中的数据

        Book book1 = (Book) session.get(Book.class, "2c2882bc42f1e93b0142f1e93d2c0000");

        System.out.println(book1);

                                                                                     

        transaction.commit();

        session.close();

    }

  

 

看log

14:43:04,171  INFO TableMetadata:66 - columns: [first_name, last_name]

14:43:04,171  INFO TableMetadata:68 - foreign keys: []

14:43:04,181  INFO TableMetadata:69 - indexes: [primary]

14:43:04,181  INFO SchemaUpdate:217 - schema update complete

Hibernate:

    select

        book0_.id as id1_0_,

        book0_.name as name1_0_,

        book0_.price as price1_0_

    from

        hbm3.tbl_book book0_

    where

        book0_.id=?

Book [id=2c2882bc42f1e93b0142f1e93d2c0000, name=Hibernate入门经典, price=23.0]

========================================================

Book [id=2c2882bc42f1e93b0142f1e93d2c0000, name=Hibernate入门经典, price=23.0]

 

第一次查詢的時候打印出了sql語句,第二次沒有sql語句。

說明:第二次沒有從DB中去讀取數據,從哪兒拿的數據呢? 就是一級緩存,第一次查詢的時候把查詢結果放進了一級緩存第二次直接取出來用。

你可能感兴趣的:(Hibernate)