简体   繁体   English

Spring Boot + JPA + Hibernate + PostgreSQL pessimistic_read与JPA本机查询

[英]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). 我需要从尚未处理的表中返回一个项目ID(在给定的时间可以有多个可用的ID,但我需要为每个请求返回唯一的ID)。

  • I am fetching first record from DB using JPA native query 我正在使用JPA本机查询从数据库中获取第一条记录

     @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 返回ID

The above scenario throws an exception stating "Invalid use of Lock" (As it doesn't support native query and only supports crud operations). 上面的情况引发了一个异常,指出“无效使用锁”(因为它不支持本机查询,仅支持Crud操作)。

Need help to use PESSIMISTIC_READ using native query for SELECT for UPDATE and SKIP locked row during race condition. 在竞争条件下,需要使用PESSIMISTIC_READ对SELECT for UPDATE和跳过锁定行使用本机查询的帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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