OPTIMISTIC_FORCE_INCREMENT: Optimistic lock, with version update.
PESSIMISTIC_FORCE_INCREMENT: Pessimistic write lock, with version update.
PESSIMISTIC_READ: Pessimistic read lock.
PESSIMISTIC_WRITE: Pessimistic write lock.
READ: Synonymous with OPTIMISTIC.
WRITE: Synonymous with OPTIMISTIC_FORCE_INCREMENT.
public interface ArticleRepository extends JpaRepository<Article, Long> {
@Lock(value = LockModeType.PESSIMISTIC_WRITE)
@Query("select a from Article a where a.id = :id")
Optional<Article> findArticleWithPessimisticLock(Long id);
}
如果是@NameQuery,则可以
@NamedQuery(name="lockArticle",query="select a from Article a where a.id = :id",lockMode = PESSIMISTIC_READ)
public class Article
public interface ArticleRepository extends JpaRepository<Article, Long> {
@Modifying
@Query(value = "update article set content= :content, version = version + 1 where id = :id and version = :version", nativeQuery = true)
int updateArticleWithVersion(Long id, String content, Long version);
}
public void postComment(Long articleId, String content) {
//get article
Optional<Article> articleOptional = articleRepository.findById(articleId);
//update with Optimistic Lock
int count = articleRepository.updateArticleWithVersion(article.getId(), content, article.getVersion());
if (count == 0) {
throw new RuntimeException("更新数据失败,请刷新重试");
}else{
articleRepository.save(article);
}
}