一.hibernate有一级缓存,二级缓存,和查询缓存。其中一二级缓存都是用来缓存对象,查询缓存是用来缓存属性。
一级
* 将echcache.xml文件拷贝到src下
* 开启二级缓存,修改hibernate.cfg.xml文件
<propertyname="hibernate.cache.use_second_level_cache">true</property>
* 指定缓存产品提供商,修改hibernate.cfg.xml文件
<propertyname="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
* 指定那些实体类使用二级缓存(两种方法)
* 在映射文件中采用<cache>标签
* 在hibernate.cfg.xml文件中,采用<class-cache>标签
如:
<hibernate-configuration> <session-factory> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.username">scott</property> <property name="hibernate.connection.password">tiger</property> <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property> <property name="format_sql">true</property> <property name="show_sql">true</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <mapping resource="com/pk/po/Person.hbm.xml"/> <class-cache usage="read-only" class="com.pk.po.Person"/> </session-factory> <!--<session-factory> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateCache</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">mysql</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="format_sql">true</property> <property name="show_sql">true</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <mapping resource="com/pk/po/Person.hbm.xml"/> <class-cache usage="read-only" class="com.pk.po.Person"/> </session-factory> --> </hibernate-configuration>
查询缓存
*在hibernate.cfg.xml文件中启用查询缓存,如:
<property name="hibernate.cache.use_query_cache">true</property>
* 指定缓存产品提供商,修改hibernate.cfg.xml文件
<propertyname="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
*在程序中必须手动启用查询缓存,如:
query.setCacheable(true);