一.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>
注意:save在註釋的那部分配置信息中是無效的,也就是對二級緩存無效,但可以再oracle中有效
查詢緩存
*在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);