缓存是介于应用程序和永久必数据存储源之间,目的是为了降低应用程序直接读写永久必数据存储源的频率,从而提高运行性能
缓存通常是在内存中的如:
Office中的Word、excel
Hibernater中的Session以及SessionFactory
ehcache.xml
<?xml version='1.0' encoding='UTF-8'?> <ehcache> <diskStore path="java.io.tempdir"/> <!-- maxElementsInMemory:允许缓存可以存储的总记录数 eternal:当前缓存是否永远不过期 overflowToDisk:当前缓存中的数据达到最大值时,是否把缓存数据写入本地硬盘 timeToIdleSeconds:当前缓存最大闲置时间,超过该时间则销毁缓存 timeToLiveSeconds:设置缓存超时时间,当缓存创建后,达到该时间就自动销毁 --> <defaultCache maxElementsInMemory = "5" eternal = "false" overflowToDisk = "true" timeToIdleSeconds = "15" timeToLiveSeconds = "120" /> </ehcache>
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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="dialect"> org.hibernate.dialect.Oracle9Dialect </property> <property name="connection.url"> jdbc:oracle:thin:@10.0.0.11:1521:ORCL </property> <property name="connection.username">demo</property> <property name="connection.password">demo</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <!-- 在Hibernate配置文件中激活ehcache二级缓存 --> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> <mapping resource="demo/entity/Bird.hbm.xml" /> <!-- 添加使用Hibernate注解的实体Bean,而不是映射文件 --> <mapping class="demo.annotations.entity.Weapon" /> </session-factory> </hibernate-configuration>
实体类配置
<?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="demo.entity.Bird" table="BIRD"> <!-- <cache usage="read-write"/> --> <id name="birdId" type="long"> <column name="id" precision="22" scale="0" /> <generator class="native" /> </id> <property name="name" type="string"> <column name="NAME" length="50" /> </property> </class> </hibernate-mapping>