Sobes.tech
Senior

How do you set a pessimistic lock on a JPA repository method without native SQL?

sobes.tech AI

Answer from AI

In JPA, to set a pessimistic lock on a repository method without using native SQL, you can use the @Lock annotation with LockModeType.PESSIMISTIC_WRITE or PESSIMISTIC_READ.

Example:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import javax.persistence.LockModeType;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select u from User u where u.id = :id")
    Optional<User> findByIdWithLock(Long id);
}

In this example, the findByIdWithLock method will use a pessimistic record lock, ensuring that other transactions cannot modify or lock this record until the current transaction is completed.

It is important that this method call occurs within a transaction (for example, annotated with @Transactional).

How do you set a pessimistic lock on a JPA repository… - sobes.tech