1.引入hibernate-release-4.2.21.Final\hibernate-release-4.2.21.Final\lib\optional\ehcache目录下的包;
2.在项目src下放EHCache的配置文件ehcache.xml,此配置文件可以直接到hibernate-release-4.2.21.Final\project\hibernate-ehcache\src\test\resources\ehcache.xml拷贝到src目录下即可;
3.①配置hibernate.cfg.xml
②配置哪些实体类的对象需要二级缓存,可以通过在hibernate.cfg.xml配置(注意,这个<class-cache>标签必须放在<mapping>标签的后面)
或者在实体类的映射文件配置;
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 配置RegionFactory为Ehcache的RegionFactory -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<mapping resource="com/gg/entity/Booktwo.hbm.xml" />
<!-- 配置哪些实体类的对象需要二级缓存 usage属性为缓存策略 -->
<class-cache usage="read-only" class="com.gy.entity.Booktwo" />
</session-factory>
</hibernate-configuration>
也可以在实体类映射文件中配置,比如:
<hibernate-mapping>
<class name="com.gg.entity.Booktwo" table="BOOKTWO">
<cache usage="read-only" />
<id name="id" type="java.lang.Short">
<column name="ID" precision="4" scale="0" />
<generator class="increment" />
</id>
......