Select for update skip locked from JPA level

前端 未结 3 1513
心在旅途
心在旅途 2021-02-19 06:42

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 w         


        
3条回答
  •  爱一瞬间的悲伤
    2021-02-19 06:56

    Hibernate provides the UPGRADE_SKIPLOCKED Lock mode.

    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);
    

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

    
       
    
    

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

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

    • MySQL
    • Postgresql
    • Oracle

    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:

    • NONE
    • OPTIMISTIC
    • OPTIMISTIC_FORCE_INCREMENT
    • PESSIMISTIC_FORCE_INCREMENT
    • PESSIMISTIC_READ
    • PESSIMISTIC_WRITE
    • READ
    • WRITE

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

    • 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

提交回复
热议问题