整理笔记---Hibernate二级缓存

来源:互联网 发布:全国汽车保有量数据 编辑:程序博客网 时间:2024/05/16 17:10

二级缓存SessionFactory缓存,取出来就不用再取了
使用Hiberante二级缓存的步骤:
①加入相关包:hibernate并没有提供相应的二级缓存的组件,所以需要加入额外的二级缓存包,常用的二级缓存包是Ehcache
这里写图片描述
②配置:在hibernate.cfg.xml中配置开启二级缓存,如下配置:

        <!-- 设置开启Hibernate二级缓存-->        <property name="hibernate.cache.use_second_level_cache">true</property>

(在hibernate4.0以下配这个)
③设置二级缓存所提供的类,如下

<!-- 设置二级缓存所提供的类 -->        <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

④在hibernate4.0之后需要设置factory class,如下

<!-- Hibernate 4.0之后设置Factory class -->        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

⑤创建对应的ehcache.xml文件,在这个文件中配置二级缓存的参数(在hibernate的下载文件中的etc目录中可以找到例子)
⑥在hibernate的配置文件中说明⑤中的配置文件中的位置,如下

 <!-- 说明ehcache的配置文件路径 -->        <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>⑦开启二级缓存    在xml的配置文件中设置

测试:

import com.xing.hibernateByXml.entity.Student;
import com.xing.hibernateByXml.util.HibernateUtil;
import org.hibernate.Session;
import org.junit.Test;

/**
* Created by Administrator on 2016/8/5.
*/
public class TestSecondCache {
@Test
public void test01(){
Session session = null;

    try {        session = HibernateUtil.openSession() ;        session.beginTransaction() ;        Student student = (Student) session.load(Student.class,1);        System.out.println("姓名:"+student.getName());        session.getTransaction().commit();    } catch (Exception e) {        e.printStackTrace();    } finally {        HibernateUtil.closeSession(session);    }    try {        session = HibernateUtil.openSession() ;        session.beginTransaction() ;        Student student = (Student) session.load(Student.class,1);        System.out.println("姓名:"+student.getName());        session.getTransaction().commit();    } catch (Exception e) {        e.printStackTrace();    } finally {        HibernateUtil.closeSession(session);    }}

}

执行结果:

Hibernate: select student0_.id as id1_2_1_, student0_.name as name2_2_1_, student0_.sex as sex3_2_1_, student0_.cid as cid4_2_1_, classroom1_.id as id1_0_0_, classroom1_.name as name2_0_0_, classroom1_.grade as grade3_0_0_, classroom1_.mid as mid4_0_0_ from t_student student0_ left outer join t_class classroom1_ on student0_.cid=classroom1_.id where student0_.id=?
姓名:王志源
姓名:王志源
“`

如上,测试中做了两次load,第一次Hibernate发了一条sql语句去获取学生信息,
因为第一次Hibernate获取到学生信息之后存储到sessionFactory二级缓存中了,
第二次查询是直接在二级缓存中去查找的。

0 0
原创粉丝点击