简体   繁体   中英

Spring boot + JPA + Hibernate + PostgreSQL pessimistic_read with JPA native query

I need to return one item id from table which has not been processed yet (At given time there can be multiple available but I need to return unique id per request).

  • I am fetching first record from DB using JPA native query

     @Lock(LockModeType.PESSIMISTIC_READ) @QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value ="5000")}) @Query(value = "SELECT id FROM item WHERE name->> 'name'=:name AND city->> 'city'=:city LIMIT 1",nativeQuery = true) public String find(@Param("name") String name, @Param("city") String city); 
  • Post that I am changing the status to processed using update query

  • Returning the ID

The above scenario throws an exception stating "Invalid use of Lock" (As it doesn't support native query and only supports crud operations).

Need help to use PESSIMISTIC_READ using native query for SELECT for UPDATE and SKIP locked row during race condition.

By Adding below line in query solved the issue.

FOR UPDATE SKIP LOCKED

@Query(value = "SELECT id FROM item WHERE name->> 'name'=:name AND city->> 'city'=:city LIMIT 1 FOR UPDATE SKIP LOCKED",nativeQuery = true)
public String find(@Param("name") String name, @Param("city") String city);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM