简体   繁体   中英

JPA close connection after exception and didn't reconnect

I am trying to retry after optimistic lock failed, but JPA close the connection and didn't reconnect it.

public String updateTnx(Integer id, String txt) {
        Tnx tnx = tnxRepository.findById(id);
        //record update by other process
        tnx.txt = txt;
        tnxRepository.save(tnx);
        return tnx.toJson();
    }

1:In this case ObjectOptimisticLockingFailureException is throw because another process have update the version column.

@Retryable(value = {ObjectOptimisticLockingFailureException.class})
    public String updateTnx(Integer id, String txt) {
        Tnx tnx = tnxRepository.findById(id);
        tnx.txt = txt;
        tnxRepository.save(tnx);
        return tnx.toJson();
    }

2:So I add retryable to the method, but I have got StatementIsClosedException.

public String updateTnx(Integer id, String txt) {
        try {
            Tnx tnx = tnxRepository.findById(id);
            tnx.txt = txt;
            tnxRepository.save(tnx);
            return tnx.toJson();
        } catch (ObjectOptimisticLockingFailureException exp) {
            Tnx tnx = tnxRepository.findById(id);
            tnx.txt = txt;
            Ttt ttt = new Ttt();
            tttRepository.save(ttt);
            tnxRepository.save(tnx);
            return tnx.toJson();
        }
    }

3: I can add StatementIsClosedException to retryable that works, but the weird thing is if I put another table to update before target one, which also works.

My question is, are JPA caching last prepared statement which cause StatementIsClosedException?

An optimistic lock exception always marks the transaction for rollback. Also, you generally cannot recover from errors thrown by the Hibernate session, as explained here .

Hence, once that ObjectOptimisticLockingFailureException is thrown, the EntityManager that was tied to the transaction is in an undefined state, and consequently, any further attempts to interact with JPA inside that very same transactional method have an undefined outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM