hibernate 二级缓存

二级缓存 可以跨session共享,

同一个sessionFactory内多个session共享。

 

<!-- 指定二级缓存策略为EHCache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 指定启用查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>

 

一级缓存和二级缓存
一级缓存 : Session级别的缓存,默认启用
二级缓存 : SessionFactory级别的缓存,默认未启用.
启用二级缓存方法:
(1)在hiberante.cfg.xml中指定二级缓存策略,默认使用EHCache
(2)引入EHCache的配置文件,从开发包的etc目录下寻找
(3)在hbm.xml的<class>元素下使用<cache>元素指定该类型对象采用二级缓存存储.
启用查询缓存方法:
(1)在hiberante.cfg.xml中指定启用查询缓存
hibernate.cache.use_query_cache true
(2)在执行query.list()方法之前,调用query.setCacheable(true).指定该查询启用查询缓存.
如何清除缓存中的对象
session.evict();
sessionFactory.evict();
sessionFactory.evictCollection();
3.批量更新,插入操作,批量删除(HQL)
参考使用文档第13章批量操作

批量插入(Batch inserts)

如果要将很多对象持久化,你必须通过经常的调用 flush() 以及稍后调用 clear() 来控制第一级缓存的大小。

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
   
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size //20,与JDBC批量设置相同
        //flush a batch of inserts and release memory:
        //将本批插入的对象立即写入数据库并释放内存
        session.flush();
        session.clear();
    }
}
   
tx.commit();
session.close();

 

posted on 2016-01-20 18:54  编世界  阅读(173)  评论(0编辑  收藏  举报