一、没有配置二级缓存情形
@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二级缓存起作用了。