选择要从JPA级别锁定的更新跳过 [英] Select for update skip locked from JPA level

查看:270
本文介绍了选择要从JPA级别锁定的更新跳过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序-具有JPA的Oracle(EclipseLink)中,我使用以下表达式锁定某些表中记录的子集:

In my application - Oracle with JPA (EclipseLink), I'm using the following expression to lock the subset of the records in some tables:

select * from MY_TABLE where MY_CONDITIONS for update skip locked

我在整个本机查询中都运行它,但是我必须为所有必需的实体编写该查询.

I run it throughout native query, but I have to write that query for all required entities.

有什么方法可以使用纯JPA跳过锁定的记录吗?我可以实施自己的锁定策略吗?

Is there any way to skip locked records using pure JPA? Can I implement my own locking policy?

我不介意更改JPA提供程序,但我想使用JPA API.

I don't mind changing JPA provider but I want to use JPA API.

推荐答案

Hibernate提供了UPGRADE_SKIPLOCKED锁定模式.

Hibernate provides the UPGRADE_SKIPLOCKED Lock mode.

使用JPA和Hibernate,根据

Using JPA and Hibernate, to produce a "SKIP_LOCKED" as per Hibernate LockMode documentation, you have to combine the PESSIMISTIC_WRITE JPA LockModeType:

entityManager.find(Department.class, 1, LockModeType.PESSIMISTIC_WRITE);

和锁定超时"设置,例如在持久性单元的persistence.xml中:

and the Lock timeout setting, like for example in persistence.xml for your persistence unit:

<properties>
   <property name="javax.persistence.query.timeout" value="-2"/>
</properties>

(请注意,您也可以为复杂查询配置此LockMode)

(Note that you can configure this LockMode for complex query as well)

跳过锁定"不是ANSI SQL的一部分.诸如以下的某些RDBMS将此作为特定功能提供:

SKIP LOCKED is not part of ANSI SQL. Some RDBMS such the following provide this as a specific feature:

  • MySQL
  • Postgresql
  • Oracle

因此,对于纯JPA,不可能在查询中指定跳过锁定". 实际上,如 LockModeType 中所述,仅JPA 2.1支持以下内容:

So with pure JPA, it is not possible to specify a "SKIP LOCKED" in queries. Indeed, as documented in LockModeType, JPA 2.1 only supports the following:

  • 乐观
  • OPTIMISTIC_FORCE_INCREMENT
  • PESSIMISTIC_FORCE_INCREMENT
  • PESSIMISTIC_READ
  • PESSIMISTIC_WRITE
  • 阅读

但是,要在查询中启用跳过锁定",您可以使用以下替代方法:

However, to enable SKIP LOCKED in your query you can use these alternatives:

  • 使用特定的JPA实现功能,例如休眠锁定模式允许通过JPA查询指定跳过锁定",这要归功于上述的 PESSIMISTIC_WRITE LockModeType锁定超时特定设置
  • 像以前一样创建本机SQL查询
  • Use specific JPA implementation feature, such as Hibernate LockMode which allows to specify the SKIP LOCKED via a JPA query, thanks to a combination of PESSIMISTIC_WRITE LockModeType Lock Timeout specific setting as described above
  • Create a native SQL query as you did

这篇关于选择要从JPA级别锁定的更新跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆