使用JPA表独占锁定 [英] Table exclusive lock with JPA
问题描述
是否可以以数据库无关的方式使用JPA专门锁定整个表(例如,不使用本机查询)?到目前为止,我只看到 EntityManager.lock(*)
但这只会锁定给定记录。
Is it possible to lock exclusively entire table with JPA in database agnostic way (without using native queries for instance)? So far I saw only EntityManager.lock(*)
but this locks only given record.
推荐答案
我认为JPA本身并不支持这种情况 - 您总是锁定单个实体或每个查询结果的实体。始终允许插入,因为它们是新实体。您可以使用本机查询来使用数据库服务器支持的SQL来触发锁定,或者您需要以编程方式锁定插入。
I don't think this is supported by JPA natively - you always lock single entity or every entity which is a result from a query. Inserts are always allowed as they are new entities. You may either use native query to trigger a lock using SQL supported by your DB server, or you need to lock your insert programmatically.
通过编程方式,我的意思是你需要在每次插入之前获取一个锁。您可以通过创建一个单独的锁实体类,每个实体用于要锁定的表,然后在每次插入之前,使用如下的读锁锁定特定实体:
By programmatically I mean that you need to acquire a lock before every insert. You may do it by creating a separate lock entity class, each entity for a table you want to lock, and then before each insert, you lock particular entity with a read lock like this:
em.createQuery("select l from TableLock l where l.entity = :entityName", TableLock.class)
.setParameter("entityName", MyEntity.class.getSimpleName())
.setLockMode(LockModeType.PESSIMISTIC_READ)
.getResultList();
em.persist(new MyEntity());
当然,您还应检查数据库中是否存在锁实体,如果不存在,则创建它首先,实体字段是您实体的名称。
Of course, you should also check if the lock entity exists in database, and if not, create it first, with entity field being the name of your entity.
这篇关于使用JPA表独占锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!