第一步,在需要缓存的持久化类的的配置文件中配置如下信息
<cache usage="read-write" region="cn.edu.model.Users"/>
例:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="cn.edu.model.Users" table="users" catalog="test"> <cache usage="read-write" region="cn.edu.model.Users"/> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="increment" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="20" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="20" /> </property> </class> </hibernate-mapping>
在SRC目录下添加ehcache.xml,信息如下
<?xml version="1.0" encoding="UTF-8"?> <!-- defaultCache节点为缺省的缓存策略 --> <!-- maxElementsInMemory 内存中最大允许存在的对象数量,eternal为设置缓存中的对象是否永远不过期 overflowToDisk 把内存中溢出的对象存放到硬盘上--> <!-- timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉 --> <!-- timeToLiveSeconds 指定缓存对象总的存活时间 diskPersistent 当jvm结束是是否持久化对象 diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间 --> <ehcache> <diskStore path="D:\cache"/> <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="60"/> <cache name="cn.edu.users" maxElementsInMemory="100" eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/> </ehcache>
在Spring的配置文件中配置如下信息
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>cn/edu/model/Users.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false<!--查询缓存--> hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider </value> </property> </bean>