JPA@Cache缓存_第1页
JPA@Cache缓存_第2页
JPA@Cache缓存_第3页
JPA@Cache缓存_第4页
JPA@Cache缓存_第5页
已阅读5页,还剩13页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、先了解一下cache基础:一级缓存Hibernate 的一级缓存是由 Session 提供的,因此它只存在于 Session 的生命周期中,当程序调用 save(),update(),saveorupdate() 等方法 及调用查询接口 list,filter,iterate 时,如 session 缓存中还不存在相应的对象, Hibernate 会把该对象加入到一级缓存中, 当 Session 关闭的时候该 Session 所管理的一级缓存也会立即被清除 Hibernate 的一级缓存是 Session 所内置的,不能被卸载,也不能进行任何配置  &#

2、160;二级缓存配置:        1 、首先要打开二级缓存,在 hibernate.cfg.xml 中添加如下配置:     <property name="hibernate.cache.use_second_level_cache">true</property>      2 、 Hibernate 的二级缓存使用第三方的缓存工具来实现,所以我们需要指定

3、 Hibernate 使用哪个        缓存工具。如下配置指定 Hibernate 使用 EhCache 缓存工具。     <property name="vider_class">org.hibernate.cache.EhCacheProvider</property>      3 、 Hibernate 在默认情况下并不

4、会对所有实体对象进行缓存,所以,我们需要指定缓存哪些对象,     在实体对象的映射文件中(相应的 <class> 标签内部),添加如下配置:     <cache usage="read-only"/>      usage="read-only" 是“只读”缓存策略。        注意,这

5、个 <cache> 标签只能放在 <class> 标签的内部,而且必须处在 <id> 标签的前面!     这个 <cache> 标签放在哪些 <class> 标签下面,就说明会多这些类的对象进行缓存        4 、对于第 3 步,有一个可选的方案是在 hibernate.cfg.xml 文件中指定哪些类的对象需要缓存,       

6、; 而不需要使用 <cache> 标签来指定。如:        在 hibernate.cfg.xml 中添加如下配置:        <class-cache class="com.bjsxt.hibernate.Classes" usage="read-only" />          

7、  注意,这个 <class-cache> 标签必须放在 <mapping> 标签的后面!       Hibernate缓存配置 _ Hibernate的缓存分为: 一级缓存:在Session级别的,在Session关闭的时候,一级缓存就失效了。 二级缓存:在SessionFactory级别的,它可以使用不同的缓存实现,如EhCache 、JBossCache、OsCache等。  缓存的注释写法如下,加在Entity的Java类

8、上: Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)  缓存的方式有四种,分别为: CacheConcurrencyStrategy.NONE CacheConcurrencyStrategy.READ_ONLY,只读模式,在此模式下,如果对数据进行更新操作,会有异常; CacheConcurrencyStrategy.READ_WRITE,读写模式在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询;&#

9、160;CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,不严格的读写模式则不会的缓存数据加锁; CacheConcurrencyStrategy.TRANSACTIONAL,事务模式指缓存支持事务,当事务回滚时,缓存也能回滚,只支持JTA环境。  另外还有如下注意事项: 1、查询缓存需要在Query的相应方法执行前加上这么一句: query.setCacheable(true); 在使用Hibernate时,获得的query有setCacheable 方法,可以设置使用缓存,但当使用JPA时

10、,javax.persistence.Query并没有setCacheable方法,此时如果JPA的实现是Hibernate时,可以将其进行如下转化,再调用setCacheable方法(如果JPA的实现是其它ORMAP框架,就不知道怎么做了)。 if(queryinstanceoforg.hibernate.ejb.QueryImpl) (org.hibernate.ejb.QueryImpl)query).getHibernateQuery().setCacheable(true); 2、还有就是查询缓存的查询执行后,会将查询结果放入二级缓存中,但是放入的形式是以ID为K

11、ey,实例作为一个Value。 3、hibernate的配置文件中需加入如下信息: <propertyname="vider_class"value="org.hibernate.cache.EhCacheProvider"/><propertyname="hibernate.cache.use_second_level_cache"value="true"/><propertyname="hibernate.cach

12、e.use_query_cache"value="true"/>  缓存映射(Cache mappings)类或者集合映射的“<cache> 元素”可以有下列形式:<cache usage="transactional|read-write|nonstrict-read-write|read-only" (1)/>(1) usage 说明了缓存的策略: transactional 、 read-write 、 nonstrict-read-write 或 read-only

13、。 另外(首选?), 你可以在hibernate.cfg.xml中指定<class-cache> 和 <collection-cache> 元素。 这里的usage 属性指明了缓存并 发策略(cache concurrency strategy) 。只读 缓存(read only)如果你的应用程序只需读取一个持久化类的实例,而无需对其修改, 那么就可以对其进行只读 缓存。这是最简单,也是实用性最好的方法。甚至在集群中,它也能完美地运作。 <class name="eg.Immutable" mutable=&quo

14、t;false"> <cache usage="read-only"/> .</class> 读/写缓存( read/write)如果应用程序需要更新数据,那么使用读/写缓存 比较合适。 如果应用程序要求“序列化事务”的隔离级别(serializable transaction isolation level),那么就决不能使用这种缓存策略。 如果在JTA环境中使用缓存,你必须指定hibernate.transaction.manager_lookup_class 属 性的值, 通过它,Hibernate

15、才能知道该应用程序中JTA的TransactionManager 的 具体策略。 在其它环境中,你必须保证在Session.close() 、或Session.disconnect() 调用前, 整个事务已经结束。 如果你想在集群环境中使用此策略,你必须保证底层的缓存实现支持锁定(locking)。Hibernate内置的缓存策略并不支持锁定功能。 <class name="eg.Cat" . > <cache usage="read-write"/> . <set name=&quo

16、t;kittens" . > <cache usage="read-write"/> . </set></class>非严格读/写缓存(nonstrict read/write)如果应用程序只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离, 那么比较适合使用非严格读/写缓存 策略。如果在JTA环境中使用该策略, 你必须为其指定hibernate.transaction.manager_lookup_class 属性的值, 在其它环境中,你必须保

17、证在Session.close() 、或Session.disconnect() 调用前, 整个事务已经结束-在jBPM 中使用不少这样的非严格读/写缓存的处理:<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC    "-/Hibernate/Hibernate Mapping DTD 3.0/EN"     "<hibernate-mapping default-access=

18、"field">   <class name="org.jbpm.context.def.VariableAccess"          table="JBPM_VARIABLEACCESS"         lazy="false">    <cache usage=&q

19、uot;nonstrict-read-write"/>    <id name="id" column="ID_"><generator class="native" /></id>        <property name="variableName" column="VARIABLENAME_" />  &#

20、160; <property name="access" column="ACCESS_" />    <property name="mappedName" column="MAPPEDNAME_" />  </class> </hibernate-mapping>它的ehcache.xml 是这样配置的:<ehcache> <defaultCache   &

21、#160;    maxElementsInMemory="100000"        eternal="true"        overflowToDisk="false"        diskPersistent="false"   

22、60;    /></ehcache>   Hibernate Annotation 中配置EhCache缓存1.  首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:xml  version ="1.0"  encoding ="UTF-8" ?>    < ehcache >   

23、0;< diskStore  path ="java.io.tmpdir" />      < defaultCache    maxElementsInMemory ="10000"     eternal ="false"        overflowToDisk =&quo

24、t;true"        timeToIdleSeconds ="300"     timeToLiveSeconds ="180"     diskPersistent ="false"    diskExpiryThreadIntervalSeconds = "120" />

25、      ehcache >     2.  在Hibernate配置文件中设置:<hibernate-configuration> <session-factory> <property name=" hibernate . vider_class">org.hibernate.cache.EhCacheProvider </property> <property name="

26、;cache.use_second_level_cache">true </property> </session-factory> </hibernate-configuration>          此外,可以把cache.use_second_level_cache设置为false关闭所有的hibernate二级缓存。但此属性对指定<cache>的类缺省为true。     3.  为

27、了使用二级缓存,需要在每一个Hibernate Entity上配置。Entity    Cache (usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)    public   class  Forest .   OneToMany (cascade=CascadeType.ALL, fetch=FetchType.EAGER)    JoinColumn (name=

28、 "CUST_ID" )    Cache (usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)    public  SortedSet getTickets()          return  tickets;      Cache (   &#

29、160;    CacheConcurrencyStrategy usage();                 (1 )        String region()  default   "" ;       &#

30、160;               (2 )        String include()  default   "all" ;                 &#

31、160; (3 )    )  (1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)(2) region (optional): 指定缓存的区域,默认是类的全限定名。利用缓存区域,可以更精确的指定每个区域的缓存超前策略。如果指定了缓存区域前缀(在 hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。(3) in

32、clude (optional): all to include all properties, non-lazy to only include non lazy properties (default all). 如果不是使用annotation的话,则是在Hbm文件中添加cache usage="read-only"本次项目使用hibernate jpa, 其配置如下:jap的persistence.xml文件<persistence xmlns="    xmlns:xsi="http:/www.w3

33、.org/2001/XMLSchema-instance"    xsi:schemaLocation="    version="1.0">        <persistence-unit name="punit" transaction-type="RESOURCE_LOCAL">       

34、 <provider >org.hibernate.ejb.HibernatePersistence</provider>        <mapping-file>IptvFeeORM.xml</mapping-file>        <properties>            &

35、lt;property name="hibernate.jdbc.batch_size" value="100"/>            <property name="hibernate.cache.use_second_level_cache"              

36、        value="true" />              <property name="vider_class"               

37、    value="net.sf.ehcache.hibernate.EhCacheProvider" />              <property name="hibernate.cache.use_minimal_puts" value="true"/>        

38、    <property name="net.sf.ehcache.configurationResourceName" value="/hibernate_ehcache.xml"/>        </properties>    </persistence-unit></persistence>cache.xml配置文件:<?xml version="1.

39、0" encoding="UTF-8"?><ehcache>    <diskStore path="./ehcache/hibernate/diskStore" />    <defaultCache maxElementsInMemory="5000000" eternal="false"        timeToIdleSeconds

40、="600" timeToLiveSeconds="600" overflowToDisk="false"        diskPersistent="false" diskExpiryThreadIntervalSeconds="1200"        memoryStoreEvictionPolicy="LRU"> 

41、;   </defaultCache></ehcache>spring引用的数据库配置文件 IptvFeeCperties :#database configjdbc.driver=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin::1521:lovejdbc.username=youjdbc.password=mejdbc.maxActive=5jdbc.maxIdle=5jpa.database=ORACLEjpa.showSql=truejp

42、a.generateDdl=falsejdbc.getdate.sql=select sysdate from dualspring 里面的配置文件:<bean id="propertyConfigurer"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <p

43、roperty name="location" value="classpath:IptvFeeCperties" />    </bean>    <bean        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> &#

44、160;  <bean id="entityManagerFactory"        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        <property name="dataSource" ref="dataSource" /&g

45、t;        <property name="persistenceXmlLocation" value="classpath:IptvFeePersistence.xml" />        <property name="jpaVendorAdapter">         

46、;   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">                <property name="database" value="$jpa.database" />    

47、0;           <property name="showSql" value="$jpa.showSql" />                <property name="generateDdl" value="$jpa.generateDdl&q

48、uot;></property>                <property name="databasePlatform" value="org.hibernate.dialect.OracleDialect" />            </bean&g

49、t;        </property>    </bean>    <bean id="dataSource" class="mons.dbcp.BasicDataSource" destroy-method="close">        <property name="drive

50、rClassName">            <value>$jdbc.driver</value>        </property>        <property name="url">     

51、0;      <value>$jdbc.url</value>        </property>        <property name="username">            <value>$jdbc.

52、username</value>        </property>        <property name="password">            <value>$jdbc.password</value>    &

53、#160;   </property>        <property name="maxActive">            <value>$jdbc.maxActive</value>        </property>        <property name="maxIdle">  

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论