JPA/Hibernate Persistence Context – JPA/Hibernate持久性语境

最后修改: 2019年 11月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Persistence providers like Hibernate make use of persistence context to manage the entity lifecycle in an application.

像Hibernate这样的持久化提供者利用持久化上下文来管理应用程序中的实体生命周期。

In this tutorial, we’ll start with the introduction of the persistence context, then we’ll see why it’s important. Finally, we’ll see the difference between transaction-scoped persistence context and extended-scoped persistence context with examples.

在本教程中,我们将从介绍持久化上下文开始,然后我们将看到为什么它很重要。最后,我们将通过实例看到事务范围的持久化上下文和扩展范围的持久化上下文之间的区别。

2. Persistence Context

2.持久性背景

Let’s take a look at the official definition of the Persistence Context:

让我们来看看Persistence Context的官方定义。

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

一个EntityManager实例与一个持久化上下文相关联。一个持久化上下文是一个实体实例的集合,对于任何持久化的实体身份,都有一个唯一的实体实例。在持久化上下文中,实体实例和它们的生命周期被管理。EntityManager API被用来创建和删除持久化实体实例,通过它们的主键查找实体,并对实体进行查询。

The above statement may seem a bit complex right now, but it will make complete sense as we proceed. The persistence context is the first-level cache where all the entities are fetched from the database or saved to the database. It sits between our application and persistent storage.

上面的语句现在看起来有点复杂,但随着我们的进行,它将变得完全合理。持久化上下文是一级缓存,所有实体都是从数据库中获取或保存到数据库中的。它位于我们的应用程序和持久化存储之间。

Persistence context keeps track of any changes made into a managed entity. If anything changes during a transaction, then the entity is marked as dirty. When the transaction completes, these changes are flushed into persistent storage.

持久性上下文会跟踪管理实体的任何变化。如果在一个事务期间有任何变化,那么该实体就会被标记为脏。当事务完成时,这些变化被刷入持久性存储。

The EntityManager is the interface that lets us interact with the persistence context. Whenever we use the EntityManager, we are actually interacting with the persistence context.

EntityManager是让我们与持久化上下文交互的接口。每当我们使用EntityManager时,我们实际上是与持久化上下文进行交互

If every change made in the entity makes a call to persistent storage, we can imagine how many calls will be made. This will lead to a performance impact because persistent storage calls are expensive.

如果实体中的每一个变化都会对持久化存储进行调用,我们可以想象会有多少调用。这将导致性能的影响,因为持久性存储的调用是昂贵的。

3. Persistence Context Type

3.持久性情境类型

Persistence contexts are available in two types:

持久性情境有两种类型。

  • Transaction-scoped persistence context
  • Extended-scoped persistence context

Let’s take a look at each.

让我们分别看一下。

3.1. Transaction-Scoped Persistence Context

3.1.事务范围内的持久化上下文

The transaction persistence context is bound to the transaction. As soon as the transaction finishes, the entities present in the persistence context will be flushed into persistent storage.

事务的持久化上下文被绑定到事务中。一旦交易完成,存在于持久化上下文中的实体将被刷入持久化存储。

transaction persistence context diagram

When we perform any operation inside the transaction, the EntityManager checks for a persistence context. If one exists, then it will be used. Otherwise, it will create a persistence context.

当我们在事务中执行任何操作时,EntityManager会检查是否有持久化上下文如果存在一个,那么它将被使用。否则,它将创建一个持久化上下文。

The default persistence context type is PersistenceContextType.TRANSACTION. To tell the EntityManager to use the transaction persistence context, we simply annotate it with @PersistenceContext:

默认的持久化上下文类型 PersistenceContextType.TRANSACTION为了告诉EntityManager使用事务持久化上下文,我们只需用@PersistenceContext来注释它。

@PersistenceContext
private EntityManager entityManager;

3.2. Extended-Scoped Persistence Context

3.2.扩展范围的持久化上下文

An extended persistence context can span across multiple transactions. We can persist the entity without the transaction but cannot flush it without a transaction.

一个扩展的持久化上下文可以横跨多个事务。我们可以在没有事务的情况下持久化实体,但不能在没有事务的情况下刷新实体。

extended persistence context diagram

To tell EntityManager to use extended-scoped persistence context, we need to apply the type attribute of @PersistenceContext:

为了告诉EntityManager使用扩展范围的持久化上下文,我们需要应用@PersistenceContexttype属性。

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

In the stateless session bean, the extended persistence context in one component is completely unaware of any persistence context of another component. This is true even if both are in same the same transaction.

在无状态会话Bean中,一个组件的扩展持久化上下文完全不知道另一个组件的任何持久化上下文即使两者都在同一个事务中,这也是真的。

Let’s say we persist some entity in a method of Component A, which is running in a transaction. We then call some method of Component B. In Component B’s method persistence context, we will not find the entity we persisted previously in the method of Component A.

假设我们在组件A的一个方法中持久化了一些实体,该组件正在事务中运行。然后我们调用组件B的一些方法。在组件B的方法持久化上下文中,我们将找不到我们之前在组件A的方法中持久化的实体。

4. Persistence Context Example

4.持久性语境实例

Now that we know enough about persistence context, it’s time to dive into an example. We’ll make different use cases with transaction persistence context and extended persistence context.

现在我们对持久化上下文有了足够的了解,是时候深入研究一个例子了。我们将用事务持久化上下文和扩展持久化上下文做不同的用例。

First, let’s create our service class, TransctionPersistenceContextUserService:

首先,让我们创建我们的服务类,TransctionPersistenceContextUserService

@Component
public class TransctionPersistenceContextUserService {

    @PersistenceContext
    private EntityManager entityManager;
    
    @Transactional
    public User insertWithTransaction(User user) {
        entityManager.persist(user);
        return user;
    }
    
    public User insertWithoutTransaction(User user) {
        entityManager.persist(user);
        return user;
    }
    
    public User find(long id) {
        return entityManager.find(User.class, id);
    }
}

The next class, ExtendedPersistenceContextUserService, is very similar to the above, except for the @PersistenceContext annotation. This time we pass PersistenceContextType.EXTENDED into the type parameter of its @PersistenceContext annotation:

下一个类,ExtendedPersistenceContextUserService,与上面的非常相似,除了@PersistenceContext注解。这次我们将PersistenceContextType.EXTENDED传入其@PersistenceContext注解的type参数。

@Component
public class ExtendedPersistenceContextUserService {

    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager entityManager;

    // Remaining code same as above
}

5. Test Cases

5.测试案例

Now that we have our service classes set up, it’s time to make different use cases with transaction persistence context and extended persistence context.

现在我们已经建立了我们的服务类,现在是时候用事务持久化上下文和扩展持久化上下文做不同的用例了。

5.1. Testing Transaction Persistence Context

5.1.测试事务持久化上下文

Let’s persist a User entity using transaction-scoped persistence context. The entity will be saved in persistent storage. We then verify by making a find call using our extended persistence context’s EntityManager:

让我们使用事务作用域持久化上下文来持久化一个User实体。该实体将被保存在持久化存储中。然后我们通过使用我们扩展的持久化上下文的EntityManager进行查找调用来进行验证。

User user = new User(121L, "Devender", "admin");
transctionPersistenceContext.insertWithTransaction(user);

User userFromTransctionPersistenceContext = transctionPersistenceContext
  .find(user.getId());
assertNotNull(userFromTransctionPersistenceContext);

User userFromExtendedPersistenceContext = extendedPersistenceContext
  .find(user.getId());
assertNotNull(userFromExtendedPersistenceContext);

When we try to insert a User entity without a transaction, then TransactionRequiredException will be thrown:

当我们试图在没有交易的情况下插入一个User实体时,就会抛出TransactionRequiredException

@Test(expected = TransactionRequiredException.class)
public void testThatUserSaveWithoutTransactionThrowException() {
    User user = new User(122L, "Devender", "admin");
    transctionPersistenceContext.insertWithoutTransaction(user);
}

5.2. Testing Extended Persistence Context

5.2.测试扩展持久性上下文

Next, let’s persist the user with an extended persistence context and without a transaction. The User entity will be saved in the persistence context (cache) but not in persistent storage:

接下来,让我们用一个扩展的持久化上下文和没有事务的情况下持久化用户。User实体将被保存在持久化上下文(缓存)中,但不在持久化存储中。

User user = new User(123L, "Devender", "admin");
extendedPersistenceContext.insertWithoutTransaction(user);

User userFromExtendedPersistenceContext = extendedPersistenceContext
  .find(user.getId());
assertNotNull(userFromExtendedPersistenceContext);

User userFromTransctionPersistenceContext = transctionPersistenceContext
  .find(user.getId());
assertNull(userFromTransctionPersistenceContext);

In the persistence context for any persistent entity identity, there will be a unique entity instance. If we try to persist another entity with the same identifier:

在任何持久化实体标识的持久化上下文中,将有一个唯一的实体实例。如果我们试图用相同的标识符来持久化另一个实体。

@Test(expected = EntityExistsException.class)
public void testThatPersistUserWithSameIdentifierThrowException() {
    User user1 = new User(126L, "Devender", "admin");
    User user2 = new User(126L, "Devender", "admin");
    extendedPersistenceContext.insertWithoutTransaction(user1);
    extendedPersistenceContext.insertWithoutTransaction(user2);
}

We’ll see EntityExistsException:

我们将看到EntityExistsException

javax.persistence.EntityExistsException: 
A different object with the same identifier value
was already associated with the session

Extended persistence context within a transaction saves the entity in persistent storage at the end of the transaction:

事务中的扩展持久化上下文在事务结束时将实体保存在持久化存储中。

User user = new User(127L, "Devender", "admin");
extendedPersistenceContext.insertWithTransaction(user);

User userFromDB = transctionPersistenceContext.find(user.getId());
assertNotNull(userFromDB);

The extended persistence context flushes the cached entities into persistent storage when used within the transaction. First, we persist the entity without a transaction. Next, we persist another entity in the transaction:

当在事务中使用时,扩展的持久化上下文将缓存的实体刷入持久化存储。首先,我们在没有事务的情况下持久化该实体。接下来,我们在事务中持久化另一个实体。

User user1 = new User(124L, "Devender", "admin");
extendedPersistenceContext.insertWithoutTransaction(user1);

User user2 = new User(125L, "Devender", "admin");
extendedPersistenceContext.insertWithTransaction(user2);

User user1FromTransctionPersistenceContext = transctionPersistenceContext
  .find(user1.getId());
assertNotNull(user1FromTransctionPersistenceContext);

User user2FromTransctionPersistenceContext = transctionPersistenceContext
  .find(user2.getId());
assertNotNull(user2FromTransctionPersistenceContext);

6. Conclusion

6.结论

In this tutorial, we gained a good understanding of the persistence context.

在本教程中,我们对持久化上下文有了充分的了解。

First, we looked at the transaction persistence context, which exists throughout the life of the transaction. Then, we looked at the extended persistence context, which can span across multiple transactions.

首先,我们看了交易持久化上下文,它存在于交易的整个生命周期。然后,我们看了扩展持久化上下文,它可以跨越多个事务。

As always, the sample code is available over on GitHub.

像往常一样,样本代码可在GitHub上获得