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>
如果是spring+hibernate的情况:
在Spring 的applicationContext.xml中配置
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<!-- 打开二级缓存 -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!-- 指定二级缓存的外部程序 ECACHE -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<!-- 打开hibernate的查询缓存 -->
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property></bean> 4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容: <cache usage="read-only" /><!--也可读写-->
<cache usage="read-write"></cache> 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
在spring+hibernate中的写法
利用Query查询
public List queryAll(int currentPage, int lineSize, String provinceName)
throws Exception {
List all = null;
String hql = "from DxCom" + provinceName
+ " as com";
Query q = this.getSession().createQuery(hql);
q.setFirstResult((currentPage - 1) * lineSize);
q.setMaxResults(lineSize);
q.setCacheable(true);//利用缓存
all = q.list();
return all;
}
|