hibernate笔记--hibernate的一级缓存

  • 缓存的概述

    • 什么是缓存

      • 缓存:是一种优化的方式,将数据存到数据库中,使用的时候直接从缓存中获取,不用通过存储源(数据库、磁盘上的源文件)。
  • hibernate的缓存

hibernate缓存中提供了优化手段:缓存和抓取策略。hibernate中提供了二种缓存机制:一级缓存、二级缓存。

  • hibernate的一级缓存

    • 概述:称为是Session级别的缓存,一级缓存生命周期与Session一致(一级缓存是由Session中的一系列Java集合构成),并且一级缓存是自带的不可卸载的。hibernate的二级缓存是SessionFactory级别的缓存,需要配置的缓存。
  • 证明一级缓存的存在

    	// 证明一级缓存的存在
    	@Test
    	public void demo3() {
    		Session session = HibernateUtils.openSession();
    		Transaction transaction = session.beginTransaction();
    
    		Customer customer1 = session.get(Customer.class, 1l);// 发送SQL语句
    		System.out.println(customer1);
    
    		Customer customer2 = session.get(Customer.class, 1l);// 不发送SQL语句,此时从缓存中获取
    		System.out.println(customer2);
    
    		System.out.println(customer1 == customer2); // 是否为同一个对象
    
    		transaction.commit();
    		session.close();
    	}
    hibernate笔记--hibernate的一级缓存
    测试一级缓存运行结果

     

  • hibernate的一级缓存的内部结构

    • 一级缓存中的特殊区域:快照区。正是因为有了快照区,持久态对象才会自动更新数据库。

      hibernate笔记--hibernate的一级缓存

       

  • 一级缓存的清空

    • clear() : 清空所有。
    • evict() : 清除指定对象。
	@Test
	// 一级缓存的清空
	public void demo5() {
		Session session = HibernateUtils.openSession();
		Transaction transaction = session.beginTransaction();

		Customer customer1 = session.get(Customer.class, 1l);// 发送SQL语句,同时放入到一级缓存中

		session.clear();// 清空所有
		session.evict(customer1);// 清空指定对象

		Customer customer2 = session.get(Customer.class, 1l);// 发送SQL语句
		System.out.println(customer1);
		System.out.println(customer2);
		transaction.commit();
		session.close();
	}
运行结果:
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_source as cust_sou3_0_0_,
        customer0_.cust_industry as cust_ind4_0_0_,
        customer0_.cust_level as cust_lev5_0_0_,
        customer0_.cust_phone as cust_pho6_0_0_,
        customer0_.cust_mobile as cust_mob7_0_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_source as cust_sou3_0_0_,
        customer0_.cust_industry as cust_ind4_0_0_,
        customer0_.cust_level as cust_lev5_0_0_,
        customer0_.cust_phone as cust_pho6_0_0_,
        customer0_.cust_mobile as cust_mob7_0_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Customer [cust_id=1, cust_name=James, cust_source=null, cust_industry=null, cust_level=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=1, cust_name=James, cust_source=null, cust_industry=null, cust_level=null, cust_phone=null, cust_mobile=null]