http://java.dzone.com/articles/jpa-caching
JPA has 2 levels of caching. The first level of caching is the persistence context.
The JPA Entity Manager maintains a set of Managed Entities in the Persistence Context.
The Entity Manager guarantees that within a single Persistence Context, for any particular database row, there will be only one object instance. However the same entity could be managed in another User's transaction, so you should use either optimistic or pessimistic locking as explained in JPA 2.0 Concurrency and locking
The code below shows that a find on a managed entity with the same id and class as another in the same persistence context , will return the same instance.
01.
@Stateless
public
ShoppingCartBean
implements
ShoppingCart {
02.
@PersistenceContext
EntityManager entityManager;
03.
public
OrderLine createOrderLine(Product product,Order order) {
04.
OrderLine orderLine =
new
OrderLine(order, product);
05.
entityManager.persist(orderLine);
06.
OrderLine orderLine2 =entityManager.find(OrderLine,
07.
orderLine.getId()));
08.
(orderLine == orderLine2)
09.
return
(orderLine);
10.
}
11.
}
The diagram below shows the life cycle of an Entity in relation to the Persistent Context.
The code below illustrates the life cycle of an Entity. A reference to a container managed EntityManager is injected using the persistence context annotation. A new order entity is created and the entity has the state of new. Persist is called, making this a managed entity. because it is a stateless session bean it is by default using container managed transactions , when this transaction commits , the order is made persistent in the database. When the orderline entity is returned at the end of the transaction it is a detached entity.
The Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions. With a Transaction scoped Persistence Context, Entities are "Detached" at the end of a transaction.
As shown below, to persist the changes on a detached entity, you call the EntityManager's merge() operation, which returns an updated managed entity, the entity updates will be persisted to the database at the end of the transaction.
An Extended Persistence Context spans multiple transactions, and the set of Entities in the Persistence Context stay Managed. This can be useful in a work flow scenario where a "conversation" with a user spans multiple requests.
The code below shows an example of a Stateful Session EJB with an Extended Persistence Context in a use case scenario to add line Items to an Order. After the Order is persisted in the createOrder method, it remains managed until the EJB remove method is called. In the addLineItem method , the Order Entity can be updated because it is managed, and the updates will be persisted at the end of the transaction.
The example below contrasts updating the Order using a transaction scoped Persistence Context verses an extended Persistence context. With the transaction scoped persistence context, an Entity Manager find must be done to look up the Order, this returns a Managed Entity which can be updated. With the Extended Persistence Context the find is not necessary. The performance advantage of not doing a database read to look up the Entity, must be weighed against the disadvantages of memory consumption for caching, and the risk of cached entities being updated by another transaction. Depending on the application and the risk of contention among concurrent transactions this may or may not give better performance / scalability.
JPA second level (L2) caching
JPA second level (L2) caching shares entity state across various persistence contexts.
JPA 1.0 did not specify support of a second level cache, however, most of the persistence providers provided support for second level cache(s). JPA 2.0 specifies support for basic cache operations with the new Cache API, which is accessible from the EntityManagerFactory, shown below:
If L2 caching is enabled, entities not found in persistence context, will be loaded from L2 cache, if found.
The advantages of L2 caching are:
- avoids database access for already loaded entities
- faster for reading frequently accessed unmodified entities
The disadvantages of L2 caching are:
- memory consumption for large amount of objects
- Stale data for updated objects
- Concurrency for write (optimistic lock exception, or pessimistic lock)
- Bad scalability for frequent or concurrently updated entities
You should configure L2 caching for entities that are:
- read often
- modified infrequently
- Not critical if stale
You should protect any data that can be concurrently modified with a locking strategy:
- Must handle optimistic lock failures on flush/commit
- configure expiration, refresh policy to minimize lock failures
The Query cache is useful for queries that are run frequently with the same parameters, for not modified tables.
The EclipseLink JPA persistence provider caching Architecture
The EclipseLink caching Architecture is shown below.
Support for second level cache in EclipseLink is turned on by default, entities read are L2 cached. You can disable the L2 cache. EclipseLink caches entities in L2, Hibernate caches entity id and state in L2. You can configure caching by Entity type or Persistence Unit with the following configuration parameters:
- Cache isolation, type, size, expiration, coordination, invalidation,refreshing
- Coordination (cluster-messaging)
- Messaging: JMS, RMI, RMI-IIOP, …
- Mode: SYNC, SYNC+NEW, INVALIDATE, NONE
The example below shows configuring the L2 cache for an entity using the @Cache annotation
The Hibernate JPA persistence provider caching Architecture
The Hibernate JPA persistence provider caching architecture is different than EclipseLink: it is not configured by default, it does not cache enities just id and state, and you can plug in different L2 caches. The diagram below shows the different L2 cache types that you can plug into Hibernate.
The configuration of the cache depends on the type of caching plugged in. The example below shows configuring the hibernate L2 cache for an entity using the @Cache annotation
分享到:
相关推荐
Spring Data Redis 用于缓存文章 Jade 作为视图模板,我极度不喜欢写 HTML 标签 Bootstrap 没有它我就不会写前端了 这是一个基于 Gradle 的项目,要想跑起来,网速要给力 Pygments 用于高亮代码 ...
本站基于 SpringBoot + SpringData JPA +Thymeleaf 实现,MySQL数据库。 引入Spring Security作为权限框架,Redis 作为部分缓存。 前端采用 BootStrap + jQuery 实现。 【功能实现】 文章、分类、标签、评论、点赞、...
Springboot学习示例 博客文章链接 (15)Spring Boot2.0 和邮件 (16)Spring Boot2.0 整合Spring Security (17)Spring Boot2.0 整合Shiro (18)Spring Boot2.0 与监控管理
进展和重点msa体系结构实现架构描述文章:滴管身份验证:buretteAuth 用户:buretteUser使用的语言和框架Sprint Boot阿帕奇杰克11 *(计划中)使用Hibernate进行JPA *(计划中)适用于mongoDB的文章API包装什么 ...
boot-multi-datasource:SpringBoot项目中的多数据源支持+redis缓存
核心框架:SpringBoot 数据库层:SpringDataJPA 安全框架:Shiro 数据库连接池:Druid 缓存:Ehcache 系统业务流程说明: 用户登录后,设置好关注领域,就可以查看领域活动、论文推送;设置关注实体后,可以看到...
从后台框架、前端模板、数据库...后台框架 SpringBoot2+、JPA 前端框架 Vue 模块框架 Thymeleaf 数据库连接池 HikariCP 缓存 Redis 限流 Guava 代理服务 Nginx 文章编辑 Markdown https://blog.52itstyle.top/index
冬眠该存储库包含演示期间或博客文章中实时使用的演示; 当前提供以下演示: HibernateORM 核心/基本:JDBC,ORM和JPA之间的简单比较核心/获取策略:“何时”(懒惰)和“如何”(获取样式) 核心/值生成:批注允许...
因为博主的能力有限,重构计划一直拖后,但是对于自己项目的目标还是有的:未来计划后台采用vuejs,前台选用更加清晰的模板引擎,在整体的项目基础上实现前后端分离,使用Redis中间件做缓存。 1.1 博客特点 使用现...
1.2 微服务(martin fowler发表了一篇文章) 5 1.3 环境约束 7 1.4 第一个Spring Boot项目(jar):HelloWorld 8 1.5 入门案例详解 11 1.5.1 POM文件 11 1.5.2 主程序类,主入口类 12 1.6 使用Spring Initializer...
JeeSite是轻量级的,简单易学,本框架以Spring Framework为核心、Spring MVC作为模型视图控制器、Spring Data JPA + Hibernate作为数据库操作层,此组合是Java界业内最经典、最优的搭配组合。前端界面风格采用了结构...
介绍 该存储库包含用于设计MicroServices的有用组件。它包括: microsvcframework-是用于解决常见技术/工程...JPA CRUD存储库 缓存Ehcache 使用REST模板的HTTP客户端 目的 此仓库的目的是提供示例,以演示如何在执行Mi
APDPlat专题文章 APDPlat是Application Product Development Platform(应用级产品开发平台)的缩写。 APDPlat提供了应用容器、多模块架构、代码生成、安装程序、认证授权、备份恢复、数据字典、web service...
主框架 (Spring-boot、Spring-data-jpa) 安全权限 Shiro 搜索工具 Lucene 缓存 Ehcache 视图模板 Freemarker 其它 Jsoup、fastjson jQuery、Seajs Bootstrap 前端框架 UEditor/Markdown编辑器 font-Awesome 字体/...
阅读标签 【】【】【】【】【】 【】【】【】【】【】 ...Boot2基础:集成JPA持久层框架,简化数据库操作 10 Boot2基础:整合Mybatis框架,集成PageHelper分页 11 Boot2基础:配置AOP切面编程,解决日志