二级缓存及外部缓存,它能够越过数个Session,通过同一个SessionFactory进行管理和维护。
要使用二级缓存,首先需要对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">
-
- <hibernate-configuration>
- <session-factory>
- ....
- <property name="hibernate.cache.provider_class">
- org.hibernate.cache.HashtableCacheProvider
- </property>
- ....
-
- </session-factory>
- </hibernate-configuration>
HashtableCache是Hibernate自己所提供的二级缓存的实现,但是由于其性能和功能有限,一般只用于开发和测试。
当然我们可以使用第三方的实现,譬如:org.hibernate.cache.EhCacheProvider,这个需要ehcathe.jar包。
修改User.hbm.xml文件:
- <?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">
- <hibernate-mapping>
- <class name="com.hb3.pack_21.model.User" table="user">
-
- <cache usage="read-write"/>
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
- <property name="name" column="name" type="java.lang.String"/>
-
- <many-to-one name="room"
- column="room_id"
- class="com.hb3.pack_21.model.Room"
- cascade="save-update"
- outer-join="true"/>
-
- </class>
- </hibernate-mapping>
这里追加的策略有read-only、read-write、nonstrict-read-write以及transactional。不同的第三方缓存实现所支持的种类是不同的,请参阅:http://www.hibernate.org/hib_docs/v3/reference/en/html/performance.html#performance-cache
在工程的classpath下追加ehcache.xml文件,内容为:
- <ehcache>
- <diskStore path="java.io.tmpdir"/>
- <defaultCache
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- />
-
- </ehcache>
测试代码如下:
- package com.hb3.pack_21;
- import java.io.IOException;
- import java.sql.SQLException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_21.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = (User) session.load(User.class, new Integer(1));
- user1.getName();
-
- session.close();
- session = sessionFactory.openSession();
-
- User user2 = (User) session.load(User.class, new Integer(1));
- user2.getName();
- session.close();
- sessionFactory.close();
- }
- }
如果不使用二级缓存机制,生成的SQL文为:
Hibernate:
select user0_.id as id0_, user0_.name as name0_0_, user0_.age as age0_0_
from user user0_ where user0_.id=?
Hibernate:
select user0_.id as id0_, user0_.name as name0_0_, user0_.age as age0_0_
from user user0_ where user0_.id=?
使用后,第二级做相同的查询会从二级缓存中读取。
当然,如果打算从二级缓存中清空对象的缓存信息,可以使用SessionFactory的evict()方法,如:
sessionFactory.evict(User.class, user.getId());
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程