Hibernate+EhCache初级应用

来源:互联网 发布:linux vi替换文件内容 编辑:程序博客网 时间:2024/04/30 17:53
1.EhCache是什么
    EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;

2.EhCache的使用注意点
    当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);

3.EhCache使用的场合
    3.1比较少更新表数据
        EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];
    3.2对并发要求不是很严格的情况
        两台机子中的缓存是不能实时同步的;

4.在项目做的实现
    4.1在工程的src目录下添加ehcache.xml文件,内容如下:
        <?xml version="1.0" encoding="UTF-8"?>
        <ehcache>    
            <diskStore path="java.io.tmpdir" />
          <defaultCache maxElementsInMemory="5"<!--缓存可以存储的总记录量-->
            eternal="false"<!--缓存是否永远不销毁-->
            overflowToDisk="true"<!--当缓存中的数据达到最大值时,是否把缓存数据写入磁盘-->
            timeToIdleSeconds="15"<!--当缓存闲置时间超过该值,则缓存自动销毁-->
                timeToLiveSeconds="120"<!--缓存创建之后,到达该缓存自动销毁-->
          />
        </ehcache>
    4.2在Hibernate.cfg.xml中的mapping标签上面加以下内容:

        <property name="show_sql">true</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
        <property name="hibernate.cache.use_query_cache">true</property>
    4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容:
       <cache usage="read-only" /><!--也可读写-->
    4.4创建DAO,内容如下:
        Session s = HibernateSessionFactory.getSession();
        Criteria c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第一次读取");
        List l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();

        s = HibernateSessionFactory.getSession();
        c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第二次读取");
        l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();
   4.5这时你会看到打印出来的信息为(表示第二次并没有去读库):
        第一次读取
        Hibernate: *******
        13
        第二次读取
        13
 
原创粉丝点击