Spring data and locking

1.1k Views Asked by At

Is it possible to have two methods in the spring-data repository - one without locking T findOne(Predicate p); together with the same but with locking @Lock(LockModeType.PESSIMISTIC_WRITE) T findOne(Predicate p);?

I wish there was something like

public interface TransactionRepository extends JpaRepository<Transaction, String>,
    QueryDslPredicateExecutor<Transaction> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @AliasFor("findOne")
    Transaction findOne_withLock(Predicate p);
}
1

There are 1 best solutions below

0
On

No, its not possible

Java does not allow you to define two functions with the same prototype. U can instead have a selector which calls the functions based on some environment variable

    public interface TransactionRepository extends JpaRepository<Transaction, String>,
            QueryDslPredicateExecutor<Transaction> {

        @Lock(LockModeType.PESSIMISTIC_WRITE)
        Transaction findOne_withLock(Predicate p);

        default Transaction findOne(Predicate p) {
            if (EvironmentCheck) {
                return findOne_withLock(p);
            }
            return findOne(p);
        }
    }