先了解一下cache基础:
一级缓存
Hibernate 的一级缓存是由 Session 提供的,因此它只存在于 Session 的生命周期中,当程序调用 save(),update(),saveorupdate() 等方法 及调用查询接口 list,filter,iterate 时,如 session 缓存中还不存在相应的对象, Hibernate 会把该对象加入到一级缓存中,
当 Session 关闭的时候该 Session 所管理的一级缓存也会立即被清除
Hibernate 的一级缓存是 Session 所内置的,不能被卸载,也不能进行任何配置
二级缓存配置:
1 、首先要打开二级缓存,在 hibernate.cfg.xml 中添加如下配置:
<property name="hibernate.cache.use_second_level_cache">true</property>
2 、 Hibernate 的二级缓存使用第三方的缓存工具来实现,所以我们需要指定 Hibernate 使用哪个
缓存工具。如下配置指定 Hibernate 使用 EhCache 缓存工具。
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
3 、 Hibernate 在默认情况下并不会对所有实体对象进行缓存,所以,我们需要指定缓存哪些对象,
在实体对象的映射文件中(相应的 <class> 标签内部),添加如下配置:
<cache usage="read-only"/>
usage="read-only" 是“只读”缓存策略。
注意,这个 <cache> 标签只能放在 <class> 标签的内部,而且必须处在 <id> 标签的前面!!!
这个 <cache> 标签放在哪些 <class> 标签下面,就说明会多这些类的对象进行缓存
4 、对于第 3 步,有一个可选的方案是在 hibernate.cfg.xml 文件中指定哪些类的对象需要缓存,
而不需要使用 <cache> 标签来指定。如:
在 hibernate.cfg.xml 中添加如下配置:
<class-cache class="com.bjsxt.hibernate.Classes" usage="read-only" />
注意,这个 <class-cache> 标签必须放在 <mapping> 标签的后面!!
Hibernate缓存配置
_____________________________________________________________________________________
Hibernate的缓存分为:
一级缓存:在Session级别的,在Session关闭的时候,一级缓存就失效了。
二级缓存:在SessionFactory级别的,它可以使用不同的缓存实现,如EhCache 、JBossCache、OsCache等。
缓存的注释写法如下,加在Entity的java类上:
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
缓存的方式有四种,分别为:
CacheConcurrencyStrategy.NONE
CacheConcurrencyStrategy.READ_ONLY,只读模式,在此模式下,如果对数据进行更新操作,会有异常;
CacheConcurrencyStrategy.READ_WRITE,读写模式在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询;
CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,不严格的读写模式则不会的缓存数据加锁;
CacheConcurrencyStrategy.TRANSACTIONAL,事务模式指缓存支持事务,当事务回滚时,缓存也能回滚,只支持JTA环境。
另外还有如下注意事项:
1、查询缓存需要在Query的相应方法执行前加上这么一句:
query.setCacheable(true);
在使用Hibernate时,获得的query有setCacheable 方法,可以设置使用缓存,但当使用JPA时,javax.persistence.Query并没有setCacheable方法,此时如果JPA的实现是Hibernate时,可以将其进行如下转化,再调用setCacheable方法(如果JPA的实现是其它ORMAP框架,就不知道怎么做了)。
if (query instanceof org.hibernate.ejb.QueryImpl) {
((org.hibernate.ejb.QueryImpl) query).getHibernateQuery().setCacheable(true);
}
2、还有就是查询缓存的查询执行后,会将查询结果放入二级缓存中,但是放入的形式是以ID为Key,实例作为一个Value。
3、hibernate的配置文件中需加入如下信息:
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.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 。
另外(首选?), 你可以在hibernate.cfg.xml中指定<class-cache> 和 <collection-cache> 元素。
这里的usage 属性指明了缓存并 发策略(cache concurrency strategy) 。
只读 缓存(read only)
如果你的应用程序只需读取一个持久化类的实例,而无需对其修改, 那么就可以对其进行只读 缓存。这是最简单,也是实用性最好的方法。甚至在集群中,它也能完美地运作。
<class name="eg.Immutable" mutable="false">
<cache usage="read-only"/>
....
</class>
读/写缓存( read/write)
如果应用程序需要更新数据,那么使用读/写缓存 比较合适。 如果应用程序要求“序列化事务”的隔离级别(serializable transaction isolation level),那么就决不能使用这种缓存策略。 如果在JTA环境中使用缓存,你必须指定hibernate.transaction.manager_lookup_class 属 性的值, 通过它,Hibernate才能知道该应用程序中JTA的TransactionManager 的 具体策略。 在其它环境中,你必须保证在Session.close() 、或Session.disconnect() 调用前, 整个事务已经结束。 如果你想在集群环境中使用此策略,你必须保证底层的缓存实现支持锁定(locking)。Hibernate内置的缓存策略并不支持锁定功能。
<class name="eg.Cat" .... >
<cache usage="read-write"/>
....
<set name="kittens" ... >
<cache usage="read-write"/>
....
</set>
</class>
非严格读/写缓存(nonstrict read/write)
如果应用程序只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离, 那么比较适合使用非严格读/写缓存 策略。如果在JTA环境中使用该策略, 你必须为其指定hibernate.transaction.manager_lookup_class 属性的值, 在其它环境中,你必须保证在Session.close() 、或Session.disconnect() 调用前, 整个事务已经结束
-------------------------------------------------------------------------
在jBPM 中使用不少这样的非严格读/写缓存的处理:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
<hibernate-mapping default-access="field">
<class name="org.jbpm.context.def.VariableAccess"
table="JBPM_VARIABLEACCESS"
lazy="false">
<cache usage="nonstrict-read-write"/>
<id name="id" column="ID_"><generator class="native" /></id>
<property name="variableName" column="VARIABLENAME_" />
<property name="access" column="ACCESS_" />
<property name="mappedName" column="MAPPEDNAME_" />
</class>
</hibernate-mapping>
它的ehcache.xml 是这样配置的:
<ehcache>
<defaultCache
maxElementsInMemory="100000"
eternal="true"
overflowToDisk="false"
diskPersistent="false"
/>
</ehcache>
Hibernate Annotation 中配置EhCache缓存
1. 首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:
xml version ="1.0" encoding ="UTF-8" ?>
< ehcache >
< diskStore path ="java.io.tmpdir" />
< defaultCache
maxElementsInMemory ="10000"
eternal ="false"
overflowToDisk ="true"
timeToIdleSeconds ="300"
timeToLiveSeconds ="180"
diskPersistent ="false"
diskExpiryThreadIntervalSeconds = "120" />
ehcache >
2. 在Hibernate配置文件中设置:
<hibernate-configuration> <session-factory> ……<property name=" hibernate . cache.provider_class">org.hibernate.cache.EhCacheProvider </property> <property name="cache.use_second_level_cache">true </property> ……</session-factory> </hibernate-configuration>
此外,可以把cache.use_second_level_cache设置为false关闭所有的hibernate二级缓存。但此属性对指定<cache>的类缺省为true。
3. 为了使用二级缓存,需要在每一个Hibernate Entity上配置。
@Entity
@Cache (usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Forest { ... }
@OneToMany (cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn (name= "CUST_ID" )
@Cache (usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public SortedSet getTickets() {
return tickets;
}
@Cache (
CacheConcurrencyStrategy usage(); (1 )
String region() default "" ; (2 )
String include() default "all" ; (3 )
)
(1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种
(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
(2) region (optional): 指定缓存的区域,默认是类的全限定名。利用缓存区域,可以更精确的指定每个区域的缓存超前策略。如果指定了缓存区域前缀(在 hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。
(3) include (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="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="punit" transaction-type="RESOURCE_LOCAL">
<provider >org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>IptvFeeORM.xml</mapping-file>
<properties>
<property name="hibernate.jdbc.batch_size" value="100"/>
<property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.use_minimal_puts" value="true"/>
<property name="net.sf.ehcache.configurationResourceName" value="/hibernate_ehcache.xml"/>
</properties>
</persistence-unit>
</persistence>
cache.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="./ehcache/hibernate/diskStore" />
<defaultCache maxElementsInMemory="5000000" eternal="false"
timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="false"
diskPersistent="false" diskExpiryThreadIntervalSeconds="1200"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
spring引用的数据库配置文件 IptvFeeConfig.properties :
#database config
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.1.1:1521:love
jdbc.username=you
jdbc.password=me
jdbc.maxActive=5
jdbc.maxIdle=5
jpa.database=ORACLE
jpa.showSql=true
jpa.generateDdl=false
jdbc.getdate.sql=select sysdate from dual
spring 里面的配置文件:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:IptvFeeConfig.properties" />
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceXmlLocation" value="classpath:IptvFeePersistence.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${jpa.database}" />
<property name="showSql" value="${jpa.showSql}" />
<property name="generateDdl" value="${jpa.generateDdl}"></property>
<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="maxActive">
<value>${jdbc.maxActive}</value>
</property>
<property name="maxIdle">
<value>${jdbc.maxIdle}</value>
</property>
<property name="testOnBorrow" value="true"/>
<property name="validationQuery" value="${jdbc.getdate.sql}"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<bean id="org.springframework.jdbc.core.JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="com.domain.repository.Repository"
class="com.repository.RepositoryJpaImpl">
<property name="jdbcTemplate" ref="org.springframework.jdbc.core.JdbcTemplate" />
</bean>
实体class
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BillContent extends AbstractPersistable implements Persistable
---------------------------------------
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cuker919/archive/2010/10/26/5966862.aspx
分享到:
相关推荐
使用JPA的二级缓存的具体实现步骤
除了对 JPA 标准的支持之外,OpenJPA 还提供了非常多的特性和工具支持让企业应用开发变得更加简单,减少开发者的工作量,包括允许数据远程传输/离线处理、数据库/对象视图统一工具、使用缓存(Cache)提升企业应用...
ZxFrame为JAVA框架-支持JPA,多级缓存,读写分离,分库分表;支持通用分布式锁;配置热更新;防缓存击穿,缓存穿透,缓存雪崩; 源码地址:https://github.com/zhouxuanGithub/zxframe *.支持JPA:继承hibernate的...
Spring Memcache 示例一个开箱即用的小示例,用于演示在 Spring MVC 驱动的 REST API 上使用 Spring 的@Cache注释。使用的库以下是演示中使用的最重要库的列表: 图书馆版本评论弹簧框架4.1.2. 发布弹簧芯弹簧数据-...
如果您必须了解一件事才能成功使用 JPA(Java 持久性 API),那就是缓存的概念。 几乎所有的事情都在某个时候归结为缓存。 不幸的是,Cache 是一个内部的东西,不是通过 JPA API 类公开的,所以从编码的角度来看它并...
Spring-Boot-Example Spring Boot 功能特性和组件系列的...不使用第三方缓存技术,ConcurrentMapCacheManager,默认使用 ConcurrentHashMap作为存储缓存 4. spring-boot-cache-ehcache2 添加 ehcache2 依赖和 ehcache.
Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化我们开发;大家一起来学习cache的用法
技术栈后端核心框架: Springboot 2.1.3数据库: MySQL 8.0.13连接池: Druid缓存: Redis + SpringBoot-CacheMarkDown处理: Flexmark其他: Lombok前端ThymeleafBootstrap 3JQueryMarkDown编辑: Editor.md弹窗: Sweet...
支持JPA,既有hibernate的便捷操作,又有mybatis的sql集中编写or管理的风格;支持乐观锁 *.支持防缓存穿透,防缓存击穿,防缓存雪崩 *.支持多层次缓存:本地一级缓存,本地全局二级缓存,远程缓存,查询缓存,方法...
Spring boot(后续用*表示) helloworld * 返回 json 数据 * 使用其他 json 转换框架 * 全局异常捕捉 * JPA 连接数据库 ...* 集成 redis 缓存 * 之 spring cache * 集成 EHCache * 分布式 Session 共享
SpringBoot2 基础教程,日志配置...基于Cache注解模式,管理Redis缓存。基于Yml配置的方式,实现文件上传逻辑。配置MongoDB数据库,实现增删改查操作。配置Actuator组件,实现系统监控。自定义启动页,项目打包指定运行环境
1.39 Spring Boot Cache理论篇 1.40 Spring Boot集成EHCache实现缓存机制 1.41 Spring Boot分布式Session状态保存Redis 1.42 Spring Boot Shiro权限管理 1.43 Spring Boot Shiro权限管理 1.44 Spring Boot Shiro权限...
- Spring 缓存,包括redis、ehcache、spring-cache、memcached、使用redis实现session共享 等。 - spring-docs - Spring 文档生成工具,包括 Swagger - spring-bussiness - Spring 业务应用,包括 AOP、过滤...
boot-multi-datasource:SpringBoot项目中的多数据源支持+redis缓存
欢迎大家留言和PR〜 提示:技术更新换代太快,本仓库仅做参考,自己的项目具体使用哪个...├── quick-cache ├── quick-config-encrypt ├── quick-docker ├── quick-dubbo ├── quick-dynamic-bean ├─
boot和ExtJs的权限管理和基础架构com.adoph.frameworkalgorithm 算法sort.SortUtils.java 简单排序工具类+++++++++++++++++++++++++++++++++++++++++++core 框架核心core.cache 缓存封装lock 锁...
6.4 整合SpringData JPA 125 6.4.1 SpringData简介 125 6.4.2 整合 126 7 Spring Boot启动配置原理 128 7.1 启动流程(Springboot 1.50版本) 128 7.1.1 创建SpringApplication对象 129 7.1.2 运行run方法 130 7.1.3...
后端:SpringBoot、Shiro、JPA、Caffeine 中间件:Redis、RabbitMQ、Druid 数据库:MySQL ## 优化思路 ### 页面查看 解决思路:从Redis缓存中查看数据,减少数据库访问 从数据可见性角度来讲,分为对所有人...
- Spring Boot 缓存,包括redis、ehcache、spring-cache、memcached、使用redis实现session共享 等。 - springboot-templates - Spring Boot 模板,包括thymeleaf、freemarker、jsp、表单校验 等。 - ...
用play.db.jpa.Blob存储上传文件 - 74 - 强制保存 - 75 - 更多公共类型generic typing问题 - 77 - 08.Play.libs库包 - 78 - 用XPath解析XML - 78 - Web Service client - 79 - Functional programming with Java功能...