Pessimistic Locking in JPA – 在JPA中悲观的锁定

最后修改: 2018年 5月 28日

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

1. Overview

1.概述

There are plenty of situations when we want to retrieve data from a database. Sometimes we want to lock it for ourselves for further processing so no one else can interrupt our actions.

有很多情况下,我们想从数据库中检索数据。有时,我们想为自己锁定它,以便进一步处理,这样就没有其他人可以打断我们的行动。

We can think of two concurrency control mechanisms that allow us to do that: setting the proper transaction isolation level or setting a lock on data that we need at the moment.

我们可以想到两种允许我们这样做的并发控制机制:设置适当的事务隔离级别或对我们目前需要的数据设置一个锁。

The transaction isolation is defined for database connections. We can configure it to retain the different degree of locking data.

事务隔离是为数据库连接定义的。我们可以配置它来保留不同程度的锁定数据。

However, the isolation level is set once the connection is created, and it affects every statement within that connection. Luckily, we can use pessimistic locking, which uses database mechanisms for reserving more granular exclusive access to the data.

然而,隔离级别是在连接创建后设置的,它影响到该连接中的每个语句。幸运的是,我们可以使用悲观锁,它使用数据库机制来保留对数据的更精细的独占访问。

We can use a pessimistic lock to ensure that no other transactions can modify or delete reserved data.

我们可以使用一个悲观的锁来确保没有其他事务可以修改或删除保留的数据。

There are two types of locks we can retain: an exclusive lock and a shared lock. We could read but not write in data when someone else holds a shared lock. In order to modify or delete the reserved data, we need to have an exclusive lock.

我们可以保留两种类型的锁:独占锁和共享锁。当别人持有共享锁时,我们可以读取但不能写进数据。为了修改或删除保留的数据,我们需要有一个独占锁。

We can acquire exclusive locks using ‘SELECT … FOR UPDATE’ statements.

我们可以使用‘SELECT … FOR UPDATE’语句获得独占锁。

2. Lock Modes

2.锁定模式

JPA specification defines three pessimistic lock modes that we’re going to discuss:

JPA规范定义了三种悲观的锁模式,我们将对此进行讨论。

  • PESSIMISTIC_READ allows us to obtain a shared lock and prevent the data from being updated or deleted.
  • PESSIMISTIC_WRITE allows us to obtain an exclusive lock and prevent the data from being read, updated or deleted.
  • PESSIMISTIC_FORCE_INCREMENT works like PESSIMISTIC_WRITE, and it additionally increments a version attribute of a versioned entity.

All of them are static members of the LockModeType class and allow transactions to obtain a database lock. They all are retained until the transaction commits or rolls back.

所有这些都是LockModeType类的静态成员,允许事务获得数据库锁。它们都会被保留,直到事务提交或回滚。

It’s worth noting that we can obtain only one lock at a time. If it’s impossible, a PersistenceException is thrown.

值得注意的是,我们一次只能获得一个锁。如果不可能,就会抛出一个PersistenceException

2.1. PESSIMISTIC_READ

2.1PESSIMISTIC_READ

Whenever we want to just read data and don’t encounter dirty reads, we could use PESSIMISTIC_READ (shared lock). We won’t be able to make any updates or deletes, though.

每当我们想只读数据,不遇到脏读时,我们可以使用PESSIMISTIC_READ(共享锁)。不过我们将不能进行任何更新或删除。

It sometimes happens that the database we use doesn’t support the PESSIMISTIC_READ lock, so we could obtain the PESSIMISTIC_WRITE lock instead.

有时,我们使用的数据库不支持PESSIMISTIC_READ锁,所以我们可以获得PESSIMISTIC_WRITE锁来代替。

2.2. PESSIMISTIC_WRITE

2.2. PESSIMISTIC_WRITE

Any transaction that needs to acquire a lock on data and make changes to it should obtain the PESSIMISTIC_WRITE lock. According to the JPA specification, holding PESSIMISTIC_WRITE lock will prevent other transactions from reading, updating or deleting the data.

任何需要获得数据锁并对其进行修改的事务都应该获得PESSIMISTIC_WRITE锁。根据JPA规范,持有PESSIMISTIC_WRITE锁将阻止其他事务读取、更新或删除该数据。

Please note that some database systems implement multi-version concurrency control that allows readers to fetch data that has been already blocked.

请注意,一些数据库系统实现了多版本并发控制,允许读者获取已经被封锁的数据。

2.3. PESSIMISTIC_FORCE_INCREMENT

2.3.PESSIMISTIC_FORCE_INCREMENT

This lock works similarly to PESSIMISTIC_WRITE, but it was introduced to cooperate with versioned entities — entities that have an attribute annotated with @Version.

这个锁的工作原理与PESSIMISTIC_WRITE类似,但它的引入是为了与有版本的实体合作–那些有@Version注释的属性的实体。

Any updates of versioned entities could be preceded with obtaining the PESSIMISTIC_FORCE_INCREMENT lock. Acquiring that lock results in updating the version column.

任何版本实体的更新都可以在获得PESSIMISTIC_FORCE_INCREMENT锁之前进行。获取该锁会导致更新版本列。

It’s up to a persistence provider to determine whether it supports PESSIMISTIC_FORCE_INCREMENT for unversioned entities or not. If it doesn’t, it throws the PersistenceException.

由持久化提供者决定它是否支持PESSIMISTIC_FORCE_INCREMENT用于未版本的实体。如果它不支持,它就会抛出 PersistenceException

2.4. Exceptions

2.4.例外情况

It’s good to know which exception may occur while working with pessimistic locking. JPA specification provides different types of exceptions:

了解在使用悲观锁时可能发生的异常是件好事。JPA规范提供了不同类型的异常。

  • PessimisticLockException indicates that obtaining a lock or converting a shared to exclusive lock fails and results in a transaction-level rollback.
  • LockTimeoutException indicates that obtaining a lock or converting a shared lock to exclusive times out and results in a statement-level rollback.
  • PersistenceException indicates that a persistence problem occurred. PersistenceException and its subtypes, except NoResultException, NonUniqueResultException, LockTimeoutException and QueryTimeoutException, mark the active transaction to be rolled back.

3. Using Pessimistic Locks

3.使用悲观的锁

There are a few possible ways to configure a pessimistic lock on a single record or group of records. Let’s see how to do it in JPA.

有几种可能的方法来配置单个记录或记录组的悲观锁。让我们看看如何在JPA中做到这一点。

3.1. Find

3.1. 查找

Find is probably the most straightforward way.

寻找可能是最直接的方式。

It’s enough to pass a LockModeType object as a parameter to the find method:

将一个LockModeType对象作为参数传递给find方法就足够了。

entityManager.find(Student.class, studentId, LockModeType.PESSIMISTIC_READ);

3.2. Query

3.2.查询

Additionally, we can use a Query object as well and call the setLockMode setter with a lock mode as a parameter:

此外,我们也可以使用一个Query对象,并调用setLockMode设置器,将锁模式作为一个参数。

Query query = entityManager.createQuery("from Student where studentId = :studentId");
query.setParameter("studentId", studentId);
query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
query.getResultList()

3.3. Explicit Locking

3.3.显式锁定

It’s also possible to manually lock the results retrieved by the find method:

也可以手动锁定查找方法所检索到的结果。

Student resultStudent = entityManager.find(Student.class, studentId);
entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_WRITE);

3.4. Refresh

3.4 刷新

If we want to overwrite the state of the entity by the refresh method, we can also set a lock:

如果我们想通过refresh方法来覆盖实体的状态,我们也可以设置一个锁。

Student resultStudent = entityManager.find(Student.class, studentId);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT);

3.5. NamedQuery

3.5 NamedQuery

@NamedQuery annotation allows us to set a lock mode as well:

@NamedQuery注解也允许我们设置一个锁定模式。

@NamedQuery(name="lockStudent",
  query="SELECT s FROM Student s WHERE s.id LIKE :studentId",
  lockMode = PESSIMISTIC_READ)

4. Lock Scope

4.锁定范围

Lock scope parameter defines how to deal with locking relationships of the locked entity. It’s possible to obtain a lock just on a single entity defined in a query or additionally block its relationships.

锁定范围参数定义了如何处理被锁定实体的锁定关系。可以只对查询中定义的单个实体获得锁定,也可以额外阻止其关系。

To configure the scope, we can use PessimisticLockScope enum. It contains two values: NORMAL and EXTENDED.

为了配置这个范围,我们可以使用PessimisticLockScope枚举。它包含两个值。NORMALEXTENDED

We can set the scope by passing a parameter ‘javax.persistence.lock.scope’ with PessimisticLockScope value as an argument to the proper method of EntityManager, Query, TypedQuery or NamedQuery:

我们可以通过向EntityManagerQueryTypedQueryNamedQuery的适当方法传递一个带有PessimisticLockScope值的参数来设置范围。

Map<String, Object> properties = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
    
entityManager.find(
  Student.class, 1L, LockModeType.PESSIMISTIC_WRITE, properties);

4.1. PessimisticLockScope.NORMAL

4.1. PessimisticLockScope.NORMAL

The PessimisticLockScope.NORMAL is the default scope. With this locking scope, we lock the entity itself. When used with joined inheritance, it also locks the ancestors.

PessimisticLockScope.NORMAL是默认的作用域。通过这个锁定作用域,我们锁定实体本身。当与联合继承一起使用时,它也锁定了祖先。

Let’s look at the sample code with two entities:

让我们看一下有两个实体的示例代码。

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {

    @Id
    private Long id;
    private String name;
    private String lastName;

    // getters and setters
}

@Entity
public class Employee extends Person {

    private BigDecimal salary;

    // getters and setters
}

When we want to obtain a lock on the Employee, we can observe the SQL query that spans over those two entities:

当我们想获得Employee上的锁时,我们可以观察跨越这两个实体的SQL查询。

SELECT t0.ID, t0.DTYPE, t0.LASTNAME, t0.NAME, t1.ID, t1.SALARY 
FROM PERSON t0, EMPLOYEE t1 
WHERE ((t0.ID = ?) AND ((t1.ID = t0.ID) AND (t0.DTYPE = ?))) FOR UPDATE

4.2. PessimisticLockScope.EXTENDED

4.2. PessimisticLockScope.EXTENDED[/em]

The EXTENDED scope covers the same functionality as NORMAL. In addition, it’s able to block related entities in a join table.

EXTENDED范围包括与NORMAL相同的功能。此外,它能够在一个连接表中阻止相关实体。

Simply put, it works with entities annotated with @ElementCollection or @OneToOne, @OneToMany, etc. with @JoinTable.

简单地说,它与用@ElementCollection@OneToOne@OneToMany等注释的实体配合使用@JoinTable

Let’s look at the sample code with the @ElementCollection annotation:

让我们看一下带有@ElementCollection注解的示例代码。

@Entity
public class Customer {

    @Id
    private Long customerId;
    private String name;
    private String lastName;
    @ElementCollection
    @CollectionTable(name = "customer_address")
    private List<Address> addressList;

    // getters and setters
}

@Embeddable
public class Address {

    private String country;
    private String city;

    // getters and setters
}

Let’s analyze some queries when searching for the Customer entity:

让我们分析一下搜索Customer实体时的一些查询。

SELECT CUSTOMERID, LASTNAME, NAME 
FROM CUSTOMER WHERE (CUSTOMERID = ?) FOR UPDATE

SELECT CITY, COUNTRY, Customer_CUSTOMERID 
FROM customer_address 
WHERE (Customer_CUSTOMERID = ?) FOR UPDATE

We can see that there are two FOR UPDATE queries that lock a row in the customer table as well as a row in the join table.

我们可以看到,有两个FOR UPDATE查询锁定了客户表中的一条记录以及连接表中的一条记录。

Another interesting fact to note is that not all persistence providers support lock scopes.

另一个值得注意的事实是,并非所有的持久性提供者都支持锁作用域。

5. Setting Lock Timeout

5.设置锁定超时

Besides setting lock scopes, we can adjust another lock parameter — timeout. The timeout value is the number of milliseconds that we want to wait for obtaining a lock until the LockTimeoutException occurs.

除了设置锁的作用域,我们还可以调整另一个锁的参数–超时。超时值是我们希望在获得锁时等待的毫秒数,直到LockTimeoutException发生。

We can change the value of timeout similarly to lock scopes, by using property ‘javax.persistence.lock.timeout’ with the proper number of milliseconds.

我们可以通过使用属性‘javax.persistence.lock.timeout’和适当的毫秒数来改变超时的值,与锁作用域类似。

It’s also possible to specify “no wait” locking by changing timeout value to zero.

也可以通过将超时值改为零来指定 “无等待 “锁定。

However, we should keep in mind that there are database drivers that don’t support setting a timeout value this way:

然而,我们应该记住,有些数据库驱动程序不支持以这种方式设置超时值。

Map<String, Object> properties = new HashMap<>(); 
map.put("javax.persistence.lock.timeout", 1000L); 

entityManager.find(
  Student.class, 1L, LockModeType.PESSIMISTIC_READ, properties);

6. Conclusion

6.结语

When setting the proper isolation level is not enough to cope with concurrent transactions, JPA gives us pessimistic locking. It enables us to isolate and orchestrate different transactions so they don’t access the same resource at the same time.

当设置适当的隔离级别不足以应对并发事务时,JPA给了我们悲观的锁定。它使我们能够隔离和协调不同的事务,使它们不会在同一时间访问同一资源。

To achieve that, we can choose between discussed types of locks and consequently modify such parameters as their scopes or timeouts.

为了达到这个目的,我们可以在讨论过的锁的类型中进行选择,从而修改它们的范围或超时等参数。

On the other hand, we should remember that understanding database locks is as important as understanding the mechanisms of underlying database systems.

另一方面,我们应该记住,理解数据库锁和理解基础数据库系统的机制一样重要。

It’s also important to remember that the behavior of pessimistic locks depends on the persistence provider we work with.

同样重要的是要记住,悲观的锁的行为取决于我们所使用的持久性提供者。

Lastly, the source code of this tutorial is available over on GitHub for Hibernate and for EclipseLink.

最后,本教程的源代码可以在GitHub上找到,用于HibernateEclipseLink