- 场景
- 解决
- Refer
DAO层框架: Hibernate
Database: PostgreSQL
需求: 悲观锁
SQL形式:select xxx from xxx where xx=xx for update
for update 会对where条件选中的记录加行级锁(where条件列必须加索引)
SQL形式已知,但问题在于:如何通过 Hibernate 拼接 for update 这段SQL?
在repository层方法上加一个@Lock注解即可。
解决@Repository public interface BookRepository implements JpaRepository{ @Lock(LockModeType.PESSIMISTIC_READ) Book findByBookIdAndBookPrice(Integer bookId, Integer price); // 错误写法, HQL(Hibernate Query Language)不支持 for update 这个SQL细节。 // @Query("select b.id, b.name, b.price from Book as b where b.id = :id and b.price = :price for update") // Book findByBookIdAndBookPrice(@param("id") Long id, @Param("price") Integer price); }
生成的SQL中,会有for updateSQL段:
select id, name, price from book where id=? and price=? for updateRefer
- Spring Data JPA进阶(五):事务和锁



