Hibernate二级缓存

本文介绍Hibernate中二级缓存的配置及使用方法,包括启动二级缓存、选择缓存提供者,并通过OsCache演示二级缓存的具体应用。此外,还介绍了如何统计二级缓存的命中率。
一 为什么需要二级缓存
因为一级缓存有限(生命周期短),所以我们需要二级缓存(SessionFactory缓存)来弥补这个问题。

二 二级缓存说明
1 需要配置
2 二级缓存是交给第三方去处理,常见的Hashtable,OSCache,EHCache
3 二级缓存的原理
4 二级缓存的对象可能放在内存,也可能放在磁盘

三 使用OsCache来演示二级缓存的使用
引入E:\hibernate-distribution-3.3.1.GA-dist\hibernate-distribution-3.3.1.GA\lib\optional\oscache中的包oscache-2.1.jar
1 步骤-配置hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd";>
<hibernate-configuration>
<session-factory>
        <property name="dialect">
                org.hibernate.dialect.MySQLDialect
        </property>
        <property name="connection.url">
                jdbc:mysql://localhost:3306/users
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">
                org.gjt.mm.mysql.Driver
        </property>
        <property name="show_sql">true</property>
        <!-- 配置让hibernate自动创建关系模型(表) -->
        <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>
            <property name="hibernate.generate_statistics">true</property>
        <mapping resource="com/hsp/domain/Student.hbm.xml" />
        <mapping resource="com/hsp/domain/Department.hbm.xml" />
        <!-- 指定哪个domain启用二级缓存 特别说明二级缓存策略:
                1. read-only
                2. read-write
                3. nonstrict-read-write
                4. transcational -->
        <class-cache class="com.hsp.domain.Student" usage="read-write"/>
</session-factory>
</hibernate-configuration>


2 步骤-拷贝一个oscache.propertis配置文件,可以使用参考文档,这里我们可以对各个属性值作一个说明
该文件来源:E:\hibernate-distribution-3.3.1.GA-dist\hibernate-distribution-3.3.1.GA\project\etc
拷贝到src目录下
3 步骤-在*.hbm.xml文件中加入使用二级缓存的策略
<cache usage="read-write"/>
也可以直接在hibernate.cfg.xml配置:
<class-cache class="cn.hsp.domain.Users" usage="read-only" />
hibernate二级缓存策略
■ 只读缓存(read-only)
■ 读写缓存(read-write) [ 银行,财务软件]
■ 不严格读写缓存(nonstrict-read-write)  [bbs 被浏览多少次]
■ 事务缓存(transactional)
4 步骤-增加测试代码
public static void main(String[] args) {
                // TODO Auto-generated method stub
                //通过获取一个sesion,让hibernate框架运行(config->加载hibernate.cfg.xml)
                Session s=null;
                Transaction tx=null;
                try {
                        //我们使用基础模板来讲解.
                        s=HibernateUtil.openSession();
                        tx=s.beginTransaction();
                        Student stu1=(Student) s.get(Student.class, 1);//1->一级缓存                
                                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();
                        Student stu1=(Student) s.get(Student.class, 1);                
                                tx.commit();
                } catch (Exception e) {
                        e.printStackTrace();
                        if(tx!=null){
                                tx.rollback();
                        }
                }finally{
                        
                        if(s!=null && s.isOpen()){
                                s.close();
                        }
                }    
        }


5 步骤-二级缓存的测试结果
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_, student0_.dept_id as dept3_0_0_ from Student student0_ where student0_.id=?
*********************************

二级缓存统计命中率
public static void main(String[] args) {
                
                // TODO Auto-generated method stub
                //通过获取一个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, 1);//1->一级缓存                
                                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, 1);                
                                tx.commit();
                        
                } catch (Exception e) {
                        e.printStackTrace();
                        if(tx!=null){
                                tx.rollback();
                        }
                }finally{
                        
                        if(s!=null && s.isOpen()){
                                s.close();
                        }
                }
                
                //完成一个统计,统计信息在SessionFactory中
                //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());
        }



7. 测试结果
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_, student0_.dept_id as dept3_0_0_ from Student student0_ where student0_.id=?
*********************************
Statistics[start time=1508422796015,sessions opened=2,sessions closed=2,transactions=2,successful transactions=2,optimistic lock failures=0,flushes=2,connections obtained=2,statements prepared=1,statements closed=1,second level cache puts=1,second level cache hits=1,second level cache misses=1,entities loaded=1,entities updated=0,entities inserted=0,entities deleted=0,entities fetched=0,collections loaded=0,collections updated=0,collections removed=0,collections recreated=0,collections fetched=0,queries executed to database=0,query cache puts=0,query cache hits=0,query cache misses=0,max query time=0]
1
1
1

【完美复现】面向配电网韧性提升的移动储能预布局与动态调度策略【IEEE33节点】(Matlab代码实现)内容概要:本文介绍了基于IEEE33节点的配电网韧性提升方法,重点研究了移动储能系统的预布局与动态调度策略。通过Matlab代码实现,提出了一种结合预配置和动态调度的两阶段优化模型,旨在应对电网故障或极端事件时快速恢复供电能力。文中采用了多种智能优化算法(如PSO、MPSO、TACPSO、SOA、GA等)进行对比分析,验证所提策略的有效性和优越性。研究不仅关注移动储能单元的初始部署位置,还深入探讨其在故障发生后的动态路径规划与电力支援过程,从而全面提升配电网的韧性水平。; 适合人群:具备电力系统基础知识和Matlab编程能力的研究生、科研人员及从事智能电网、能源系统优化等相关领域的工程技术人员。; 使用场景及目标:①用于科研复现,特别是IEEE顶刊或SCI一区论文中关于配电网韧性、应急电源调度的研究;②支撑电力系统在灾害或故障条件下的恢复力优化设计,提升实际电网应对突发事件的能力;③为移动储能系统在智能配电网中的应用提供理论依据和技术支持。; 阅读建议:建议读者结合提供的Matlab代码逐模块分析,重点关注目标函数建模、约束条件设置以及智能算法的实现细节。同时推荐参考文中提及的MPS预配置与动态调度上下两部分,系统掌握完整的技术路线,并可通过替换不同算法或测试系统进一步拓展研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值