Hibernate二级缓存配置

一、没有配置二级缓存情形

    @Test
    public void test(){
        Employee employee = (Employee) session.get(Employee.class, 1);

        Employee employee2 = (Employee) session.get(Employee.class, 1);

        System.out.println(employee);

        System.out.println(employee2);

    }

因为hibernate缓存的原因,实际上只会发送一条sql语句。

现在再来实验一下,得到employee2前清楚session缓存

    @Test
    public void test2(){
        Employee employee = (Employee) session.get(Employee.class, 1);

        session.clear();
        Employee employee2 = (Employee) session.get(Employee.class, 1);

        System.out.println(employee);

        System.out.println(employee2);

    }
Hibernate: 
    select
        employee0_.ID as ID1_1_0_,
        employee0_.NAME as NAME2_1_0_,
        employee0_.DEPT_ID as DEPT_ID3_1_0_ 
    from
        EMPLOYEES employee0_ 
    where
        employee0_.ID=?
Hibernate: 
    select
        employee0_.ID as ID1_1_0_,
        employee0_.NAME as NAME2_1_0_,
        employee0_.DEPT_ID as DEPT_ID3_1_0_ 
    from
        EMPLOYEES employee0_ 
    where
        employee0_.ID=?
Employee [id=1]
Employee [id=1]

我们看到发送了两条sql语句。

再来看另一种情形

@Test
    public void test3(){
        Employee employee = (Employee) session.get(Employee.class, 1);

        session.close();
        session = sessionFactory.openSession();
        Employee employee2 = (Employee) session.get(Employee.class, 1);

        System.out.println(employee);

        System.out.println(employee2);

    }

第二次get之前关闭session,然后开启一个session,前后两个session是不一样的。这样发送了两条select语句。问题:可不可以开启两个不同的session时,如果是相同的OID,则只发送一条sql语句,即对于不同的session,hibernate仍然能够缓存?

答案是配置二级缓存。sessionFactory级别。

2、配置hibernate的二级缓存
(1)导入相应的jra包
ehcache-core-2.4.3.jar
hibernate-ehcache-4.2.4.Final.jar
slf4j-api-1.6.1.jar
(2)配置ehcache.xml文件—使用默认的配置

(3)配置hibernate.cfg.xml文件
①. 启用二级缓存

<property name="cache.use_second_level_cache">true</property>

②.配置使用的二级缓存的产品

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

③.配置启用二级缓存的类

<class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
        <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Department"/>

再执行test3方法时,我们可以看到只发送了一条sql语句。hibernate二级缓存起作用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值