Spring Boot JPA @Lock TransactionRequiredException

Spring Boot JPA About 953 words

错误信息

Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress

Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress

错误代码

使用了@Lock实现悲观锁:select...for update

import javax.persistence.LockModeType;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;

public interface UserRepo extends JpaRepository<User, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    User findByIdIs(Long id);

}

原因

需要使用事务。

解决

此处只是演示解决方法,即:添加@Transactional注解。javaxspring包下的@Transactional都可以。

一般会在调用Repo的方法的地方标注@Transactional事务。

public interface UserRepo extends JpaRepository<User, Long> {

    @Transactional
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    User findByIdIs(Long id);

}
Views: 1,143 · Posted: 2023-02-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today On History
Browsing Refresh