Hibernate学习之二级缓存

为什么需要二级缓存?
因为一级缓存有限(生命周期短),所以我们需要二级缓存(SessionFactory缓存)来弥补这个问题
需要配置
二级缓存是交给第三方去处理,常见的Hashtable , OSCache , EHCache
二级缓存的对象可能放在内存,也可能放在磁盘.

在*.hbm.xml文件中加入使用二级缓存的策略:
<cache usage="read-write"/>
也可以直接在hibernate.cfg.xml配置:
<class-cache class="cn.cz.domain.Users" usage="read-only" />

案例:
使用OsCache 来演示二级缓存的使用.
配置二级缓存
对配置说明:
<property name="hbm2ddl.auto">update</property>
    <!-- 启动二级缓存 -->
    <property name="cache.use_second_level_cache">true</property>
    <!-- 指定使用哪种二级缓存 -->
    <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
    <mapping resource="com/cz/domain/Department.hbm.xml" />
    <mapping resource="com/cz/domain/Student.hbm.xml" />
    <!-- 指定哪个domain启用二级缓存
    特别说明二级缓存策略:
    hibernate二级缓存策略
    只读缓存(read-only)
    读写缓存(read-write) [ 银行,财务软件]
     不严格读写缓存(nonstrict-read-write)  [bbs 被浏览多少次]
    事务缓存(transactional)
    -->
    <class-cache class="com.hsp.domain.Student" usage="read-write"/>

oscache.properties 文件放在 src目录下,这样你可以指定放入二级缓存的对象capacity 大小. 默认1000

如果报错还要再引入Hibernate的log4j.jar


使用:
        //通过获取一个sesion,让hibernate框架运行(config->加载hibernate.cfg.xml)
        Session s=null;
        Transaction tx=null;
       
        try {
            //使用基础模板
            s=HibernateUtil.openSession();
            tx=s.beginTransaction();
           
            //查询45号学生
       
            Student stu1=(Student) s.get(Student.class, 45);//45->一级缓存       
            System.out.println(stu1.getName());
           
           
            tx.commit();
           
        } catch (Exception e) {
            e.printStackTrace();
            if(tx!=null){
                tx.rollback();
            }
        }finally{
           
            if(s!=null && s.isOpen()){
                s.close();
            }
        }
       
        System.out.println("*********************************");
        try {
            //使用基础模板
            s=HibernateUtil.openSession();
            tx=s.beginTransaction();
           
            //查询45号学生
       
            Student stu1=(Student) s.get(Student.class, 45);   
            System.out.println(stu1.getName());
           
            Student stu3=(Student) s.get(Student.class, 46);   
            System.out.println(stu3.getName());
                tx.commit();
           
        } catch (Exception e) {
            e.printStackTrace();
            if(tx!=null){
                tx.rollback();
            }
        }finally{
           
            if(s!=null && s.isOpen()){
                s.close();
            }
        }
       
        //完成一个统计,统计的信息在Sessfactory
        //获取SessionFactory对象.
        Statistics statistics= HibernateUtil.getSessionFactory().getStatistics();
        System.out.println(statistics);
        System.out.println("放入"+statistics.getSecondLevelCachePutCount());
        System.out.println("命中"+statistics.getSecondLevelCacheHitCount());
        System.out.println("错过"+statistics.getSecondLevelCacheMissCount());

在配置了二级缓存后,要注意可以通过 Statistics,查看你的配置命中率高不高

HibernateUtil.java:

package com.sina.util;
import java.util.List;



import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
	private static SessionFactory sessionFactory=null;
	//使用线程局部模式
	private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
	private HibernateUtil(){};
	static {
		sessionFactory=new Configuration().configure().buildSessionFactory();
	}

        //获取SessionFactory
        public static SessionFactory getSessionFactory(){
                 return SessionFactory;
        }

 
       //获取全新的全新的sesession
	public static Session openSession(){
		return sessionFactory.openSession();
	}
	//获取和线程关联的session
	public static Session getCurrentSession(){
		
		Session session=threadLocal.get();
		//判断是否得到
		if(session==null){
			session=sessionFactory.openSession();
			//把session对象设置到 threadLocal,相当于该session已经和线程绑定
			threadLocal.set(session);
		}
		return session;		
	}
	
	public static void closeCurrentSession(){
		
		Session s=getCurrentSession();
		
		if(s!=null&& s.isOpen() ){
			s.close();
			threadLocal.set(null);
		}
	}
}

猜你喜欢

转载自chenzheng8975.iteye.com/blog/1683861
今日推荐