Hibernate二级缓存调用

原文链接:http://guxiangdiyu87.iteye.com/blog/1630638

注:其实hibernate的二级缓存还有其他的解决方案,这个只是现阶段使用得比较多的而已。二级缓存属于sessionfactory级别的缓存,基本就同属全局缓存了。如果使用得当能够极大的提供使用效率,但是,二级缓存 显而易见得会造成数据刷新延迟。。之类的各种问题,这个得让大家自己综合自己的业务水平选择比较恰当的解决方案才是王道。


Hibernate中的一级缓存是Session范围内的,而二级缓存是SessionFactory范围的,
需要使用第三方的实现。本文通过注解的方式为Hibernate配置二级缓存,采用的
第三方实现是Ehcache。

项目的结构如下,本文主要用到了:
Account.java
CachedAccount.java
SecondaryCache.java
ehcache.xml
hibernate.cfg.xml



为一个实体类进行二级缓存配置可以分为三步:

1.首先,要在hibernate.cfg.xml中开启二级缓存,并设置好Hibernate的provider。
因为Hibernate没有自己实现二级缓存,而只是为不同的第三方缓存提供了不同
的provider类。
Html代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>  
  8.         <property name="hibernate.connection.url">jdbc:sqlserver://192.168.1.102:1433;databaseName=Bank</property>  
  9.         <property name="hibernate.connection.username">sa</property>  
  10.         <property name="hibernate.connection.password">1qaz2wsx</property>  
  11.         <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>  
  12.         <property name="connection.pool_size">1</property>  
  13.         <property name="show_sql">true</property>  
  14.         <!-- <property name="hbm2ddl.auto">create</property> -->  
  15.           
  16.         <property name="hibernate.cache.use_second_level_cache">true</property>    
  17.         <property name="hibernate.cache.use_query_cache">true</property>  
  18.         <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
  19.             
  20.     </session-factory>  
  21. </hibernate-configuration>  
虽然已经启用了二级缓存,但是它不会默认就对所有实体类都进行缓存,那样
的话内存开销太大,所有接下来我们还需要对具体的实体类进行缓存策略和
并发策略的配置。

2.编写ehcache.xml的配置文件,在这里除了可以对默认缓存策略进行配置外,
还可以对每个实体类进行不同的配置。具体可以配置的选项请参加ehcache的
xml schema文件:http://ehcache.org/ehcache.xsd 
Html代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache>  
  3.   
  4.     <!-- 如果内存放不下,就放到磁盘上的一个路径 -->  
  5.     <!-- <diskStore path="e:/ehcache" /> -->  
  6.   
  7.     <!-- 内存中存放最多的对象个数 -->  
  8.     <defaultCache maxElementsInMemory="2000" eternal="false"  
  9.         timeToIdleSeconds="50" timeToLiveSeconds="60" overflowToDisk="false" />  
  10.           
  11.     <!-- 保存的对象 -->  
  12.     <cache name="com.cdai.orm.hibernate.annotation.Account" maxElementsInMemory="200"  
  13.         eternal="false" timeToIdleSeconds="50" timeToLiveSeconds="60"  
  14.         overflowToDisk="false" />  
  15.           
  16.     <cache name="com.cdai.orm.hibernate.transaction.AccountVersion" maxElementsInMemory="0"/>  
  17.       
  18. </ehcache>  

3.在实体类上加上Cache注解,并指定并发策略。因为二级缓存是SessionFactory
范围内的,所以不同Session同时修改一个实体类就会产生并发问题。正因为对共享
数据的并发访问从底层数据库提前到了应用程序中的二级缓存层,所以在数据库
层面上涉及的各种并发问题,提前在二级缓存应用程序层上出现了。
Java代码   收藏代码
  1. package com.cdai.orm.hibernate.cache;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.Id;  
  8. import javax.persistence.Table;  
  9.   
  10. import org.hibernate.annotations.Cache;  
  11. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  12.   
  13. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)  
  14. @Entity  
  15. @Table(name = "tb_cached_account")  
  16. public class CachedAccount implements Serializable {  
  17.   
  18.     private static final long serialVersionUID = 5018821760412231859L;  
  19.   
  20.     @Id  
  21.     @Column(name = "col_id")  
  22.     private long id;  
  23.       
  24.     @Column(name = "col_balance")  
  25.     private long balance;  
  26.   
  27.     public CachedAccount() {  
  28.     }  
  29.       
  30.     public CachedAccount(long id, long balance) {  
  31.         this.id = id;  
  32.         this.balance = balance;  
  33.     }  
  34.   
  35.     public long getId() {  
  36.         return id;  
  37.     }  
  38.   
  39.     public void setId(long id) {  
  40.         this.id = id;  
  41.     }  
  42.   
  43.     public long getBalance() {  
  44.         return balance;  
  45.     }  
  46.   
  47.     public void setBalance(long balance) {  
  48.         this.balance = balance;  
  49.     }  
  50.   
  51.     @Override  
  52.     public String toString() {  
  53.         return "CachedAccount [id=" + id + ", balance=" + balance + "]";  
  54.     }  
  55.       
  56. }  
CachedAccount.java只是比Account.java多了Cache注解,其余代码完全相同。 

下面来看一个例子,验证二级缓存是否配置成功。
Java代码   收藏代码
  1. package com.cdai.orm.hibernate.cache;  
  2.   
  3. import org.hibernate.Query;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.SessionFactory;  
  6. import org.hibernate.cfg.AnnotationConfiguration;  
  7.   
  8. import com.cdai.orm.hibernate.annotation.Account;  
  9.   
  10. public class SecondaryCache {  
  11.   
  12.     public static void main(String[] args) {  
  13.   
  14.         SessionFactory sessionFactory =   
  15.                 new AnnotationConfiguration().  
  16.                     addFile("hibernate/hibernate.cfg.xml").               
  17.                     configure().  
  18.                     addAnnotatedClass(CachedAccount.class).  
  19.                     addAnnotatedClass(Account.class).  
  20.                     buildSessionFactory();  
  21.   
  22.         Session session1 = sessionFactory.openSession();  
  23.         Session session2 = sessionFactory.openSession();  
  24.   
  25.         // Cached get  
  26.         CachedAccount accountc1 = (CachedAccount) session1.get(CachedAccount.classnew Long(1));  
  27.         CachedAccount accountc2 = (CachedAccount) session2.get(CachedAccount.classnew Long(1));  
  28.         CachedAccount accountc3 = (CachedAccount) session2.get(CachedAccount.classnew Long(1));  
  29.         System.out.println(accountc1 == accountc2);  
  30.         System.out.println(accountc3 == accountc2);  
  31.   
  32.         // Cached query  
  33.         Query query = session1.createQuery(" from CachedAccount acct where acct.id=:id ");  
  34.         query.setCacheable(true);  
  35.         query.setParameter("id"new Long(1));  
  36.         accountc1 = (CachedAccount) query.uniqueResult();  
  37.         System.out.println(accountc1);  
  38.           
  39.         query.setParameter("id"new Long(1));  
  40.         accountc1 = (CachedAccount) query.uniqueResult();  
  41.         System.out.println(accountc1);  
  42.           
  43.         // Not-cached  
  44.         Account account1 = (Account) session1.get(Account.classnew Long(1));  
  45.         Account account2 = (Account) session2.get(Account.classnew Long(1));  
  46.         System.out.println(account1 == account2);  
  47.           
  48.         session1.close();  
  49.         session2.close();  
  50.         sessionFactory.close();  
  51.     }  
  52.   
  53. }  

log输出为:

Hibernate: select cachedacco0_.col_id as col1_0_0_, cachedacco0_.col_balance as col2_0_0_ from tb_cached_account cachedacco0_ where cachedacco0_.col_id=?
false
true
Hibernate: select cachedacco0_.col_id as col1_0_, cachedacco0_.col_balance as col2_0_ from tb_cached_account cachedacco0_ where cachedacco0_.col_id=?
CachedAccount [id=1, balance=1000]
CachedAccount [id=1, balance=1000]
Hibernate: select account0_.col_id as col1_1_0_, account0_.col_balance as col2_1_0_ from tb_account account0_ where account0_.col_id=?
Hibernate: select account0_.col_id as col1_1_0_, account0_.col_balance as col2_1_0_ from tb_account account0_ where account0_.col_id=?
false

可以看到对实体类CachedAccount配置了Cache注解,二级缓存对它已经生效,
三次get()调用只执行了一次真正的SQL查询语句。而之后的Account实体类每次
调用get()都会执行一次SQL语句。

另外我们也注意到,虽然CachedAccount已经保存在二级缓存中,但是我们在不同
Session查询得到的却是不同的对象。CachedAccount不是直接缓存在二级缓存中的
吗?这是为什么呢?

因为如果直接将实体类对象缓存在二级缓存中,然后将同一个实体类返回给不同的
Session的话,虽然比较节省缓存,但是当不同的Session都可能长时间操作这一个对象
,这样就需要对这些不同线程中的操作进行同步,性能会很差。

所以二级缓存一般只是保存散装的数据(对象的属性),当Session加载时将散装数据
组装成一个新的实体类对象返回给它。虽然耗费内存,但是不需要同步了,二级缓存
只需要在每个Session获得对象时同步,之后每个Session的事务都操纵各自的对象,就
无需同步了。

此外,对查询缓存还要注意一点,除了在hibernate.cfg.xml中开启外,还要在查询前
调用query.setCacheable(true);才能使用查询缓存。


结束语

摘录一段别人的总结:

“不要想当然的以为缓存一定能提高性能,仅仅在你能够驾驭它并且条件合适的情况下才是这样的。
hibernate的二级缓存限制还是比较多的,不方便用jdbc可能会大大的降低更新性能。在不了解原理
的情况下乱用,可能会有1+N的问题。不当的使用还可能导致读出脏数据。 如果受不了hibernate的
诸多限制,那么还是自己在应用程序的层面上做缓存吧。 

在越高的层面上做缓存,效果就会越好。就好像尽管磁盘有缓存,数据库还是要实现自己的缓存,
尽管数据库有缓存,咱们的应用程序还是要做缓存。因为底层的缓存它并不知道高层要用这些数据
干什么,只能做的比较通用,而高层可以有针对性的实现缓存,所以在更高的级别上做缓存,效果也
要好些吧。”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值