配置指定要使用二级缓存的方式有两种
a) 在hibernate.cfg.xml中指定要使用二级缓存的类 <!-- 类级二级缓存:指定哪些类要使用二级缓存 -->
<class-cache usage="read-write" class="com.restfullDemo.model.User"/>
<class-cache usage="read-write" class="com.restfullDemo.model.Department"/>
<!-- 集合级二级缓存,指定哪个类中的集合属性使用二级缓级,前提是该属性的类必须已设置二级缓存中 -->
<collection-cache usage="read-write" collection="com.restfullDemo.model.Department.users"/>
b) 也可以在类的对应映射文件中时行配置
?
类的二级缓存配置
<class name="com.restfullDemo.model.User" table="t_user">
<cache usage="read-write"/>
......
</class>
集合级的二级缓存配置
<hibernate-mapping>
<class name="com.restfullDemo.model.Department" table="t_department">
<id name="id" type="int">
<column name="id" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<set name="users" table="t_user" inverse="false" lazy="false" >
<cache usage="read-write"/>
<key>
<column name="dpt_id" />
</key>
<one-to-many class="com.restfullDemo.model.User" />
</set>
</class>
</hibernate-mapping>
实例:
?
public class User {
private int id;
private String name;
private int age;
private Department dpt;
setter、getter.....
}
public class Department {
private int id;
private String name;
private Set<User> users = new HashSet<User>();
setter、getter......
}
hibernet.cfg.xml
?
<?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 name="">
<property name="hibernate.dialect">xxxxx</property>
<property name="hibernate.connection.driver_class">xxxx</property>
<property name="hibernate.connection.url">xxxx</property>
<property name="hibernate.connection.username">xxxx</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 缓存设置 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.internal.EhcacheRegionFactory</property>
<!-- 映射文件配置 -->
<mapping resource="com/restfullDemo/mappingResources/User.hbm.xml"/>
<mapping resource="com/restfullDemo/mappingResources/Department.hbm.xml"/>
<!-- 类级二级缓存:指定哪些类要使用二级缓存 -->
<class-cache usage="read-write" class="com.restfullDemo.model.User"/>
<class-cache usage="read-write" class="com.restfullDemo.model.Department"/>
<!-- 集合级二级缓存,指定哪个类中的集合属性使用二级缓级,前提是该属性的类必须已设置二级缓存中 -->
<collection-cache usage="read-write" collection="com.restfullDemo.model.Department.users"/>
</session-factory>
</hibernate-configuration>
?