1、why(为何要用Hibernate缓存?) java
Hibernate是一个持久层框架,常常访问物理数据库。为了下降应用程序对物理数据源访问的频次,从而提升应用程序的运行性能。
2、what(Hibernate缓存原理是怎样的?)Hibernate缓存包括两大类:Hibernate一级缓存和Hibernate二级缓存。 sql
1.Hibernate一级缓存又称为“Session的缓存”。
Session内置不能被卸载,Session的缓存是事务范围的缓存(Session对象的生命周期一般对应一个数据库事务或者一个应用事务)。一级缓存中,持久化类的每一个实例都具备惟一的OID。
2.Hibernate二级缓存又称为“SessionFactory的缓存”。
因为SessionFactory对象的生命周期和应用程序的整个过程对应,所以Hibernate二级缓存是进程范围或者集群范围的缓存,有可能出现并发问题,所以须要采用适当的并发访问策略,该策略为被缓存的数据提供了事务隔离级别。
第二级缓存是可选的,是一个可配置的插件,默认下SessionFactory不会启用这个插件。
Hibernate提供了org.hibernate.cache.CacheProvider接口,它充当缓存插件与Hibernate之间的适配器。
适合存放到第二级缓存中的数据?
(1) 不多被修改的数据
(2) 不是很重要的数据,容许出现偶尔并发的数据
(3) 不会被并发访问的数据
(4) 常量数据
不适合存放到第二级缓存的数据?
(1) 常常被修改的数据
(2) 绝对不容许出现并发访问的数据,如财务数据,绝对不容许出现并发
(3) 与其余应用共享的数据 数据库
Hibernate session就是java.sql.Connection的一层高级封装,一个session对应了一个Connection。
http请求结束后正确的关闭session(过滤器实现了session的正常关闭);延迟加载必须保证是同一个session(session绑定在ThreadLocal)。 缓存
4.Hibernate查找对象如何应用缓存?
当Hibernate根据ID访问数据对象的时候,首先从Session一级缓存中查; session
查不到,若是配置了二级缓存,那么从二级缓存中查; 并发
若是都查不到,再查询数据库,把结果按照ID放入到缓存删除、更新、增长数据的时候,同时更新缓存。 app
3、how(Hibernate的缓存机制如何应用?) 框架
1. 一级缓存的管理:2. 一级缓存应用: ide
save(): 当session对象调用save()方法保存一个对象后,该对象会被放入到session的缓存中。
get()和load(): 当session对象调用get()或load()方法从数据库取出一个对象后,该对象也会被放入到session的缓存中。 使用HQL和QBC等从数据库中查询数据。 性能
public class Client { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null; try { /*开启一个事务*/ tx = session.beginTransaction(); /*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象*/ Customer customer1 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002"); System.out.println("customer.getUsername is"+customer1.getUsername()); /*事务提交*/ tx.commit(); System.out.println("-------------------------------------"); /*开启一个新事务*/ tx = session.beginTransaction(); /*从数据库中获取id="402881e534fa5a440134fa5a45340002"的Customer对象*/ Customer customer2 = (Customer)session.get(Customer.class, "402881e534fa5a440134fa5a45340002"); System.out.println("customer2.getUsername is"+customer2.getUsername()); /*事务提交*/ tx.commit(); System.out.println("-------------------------------------"); /*比较两个get()方法获取的对象是不是同一个对象*/ System.out.println("customer1 == customer2 result is "+(customer1==customer2)); } catch (Exception e) { if(tx!=null) { tx.rollback(); } } finally { session.close(); } } }结果:
Hibernate: select customer0_.id as id0_0_, customer0_.username as username0_0_, customer0_.balance as balance0_0_ from customer customer0_ where customer0_.id=? customer.getUsername islisi ------------------------------------- customer2.getUsername islisi ------------------------------------- customer1 == customer2 result is true输出结果中只包含了一条SELECT SQL语句,并且customer1 == customer2 result is true说明两个取出来的对象是同一个对象。其原理是:第一次调用get()方法, Hibernate先检索缓存中是否有该查找对象,发现没有,Hibernate发送SELECT语句到数据库中取出相应的对象,而后将该对象放入缓存 中,以便下次使用,第二次调用get()方法,Hibernate先检索缓存中是否有该查找对象,发现正好有该查找对象,就从缓存中取出来,再也不去数据库 中检索。 3. 二级缓存的管理:
4. 二级缓存的配置
经常使用的二级缓存插件
EHCache org.hibernate.cache.EhCacheProvider
OSCache org.hibernate.cache.OSCacheProvider
SwarmCahe org.hibernate.cache.SwarmCacheProvider
JBossCache org.hibernate.cache.TreeCacheProvider
<!-- EHCache的配置,hibernate.cfg.xml --> <hibernate-configuration> <session-factory> <!-- 设置二级缓存插件EHCache的Provider类--> <property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> <!-- 启动"查询缓存" --> <property name="hibernate.cache.use_query_cache"> true </property> </session-factory> </hibernate-configuration>
<!-- ehcache.xml --> <?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 缓存到硬盘的路径 --> <diskStore path="d:/ehcache"></diskStore> <!-- 默认设置 maxElementsInMemory : 在內存中最大緩存的对象数量。 eternal : 缓存的对象是否永远不变。 timeToIdleSeconds :能够操做对象的时间。 timeToLiveSeconds :缓存中对象的生命周期,时间到后查询数据会从数据库中读取。 overflowToDisk :内存满了,是否要缓存到硬盘。 --> <defaultCache maxElementsInMemory="200" eternal="false" timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></defaultCache> <!-- 指定缓存的对象。 下面出现的的属性覆盖上面出现的,没出现的继承上面的。 --> <cache name="com.suxiaolei.hibernate.pojos.Order" maxElementsInMemory="200" eternal="false" timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="true"></cache> </ehcache>
<!-- *.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> <!-- 设置该持久化类的二级缓存并发访问策略 read-only read-write nonstrict-read-write transactional--> <cache usage="read-write"/> </class> </hibernate-mapping>若存在一对多的关系,想要在在获取一方的时候将关联的多方缓存起来,须要在集合属性下添加<cache>子标签,这里须要将关联的对象的 hbm文件中必须在存在<class>标签下也添加<cache>标签,否则Hibernate只会缓存OID。
<hibernate-mapping> <class name="com.suxiaolei.hibernate.pojos.Customer" table="customer"> <!-- 主键设置 --> <id name="id" type="string"> <column name="id"></column> <generator class="uuid"></generator> </id> <!-- 属性设置 --> <property name="username" column="username" type="string"></property> <property name="balance" column="balance" type="integer"></property> <set name="orders" inverse="true" cascade="all" lazy="false" fetch="join"> <cache usage="read-only"/> <key column="customer_id" ></key> <one-to-many class="com.suxiaolei.hibernate.pojos.Order"/> </set> </class> </hibernate-mapping>