0

We are using JdbcTemplate to save data in some DAO's and JPA in some DAO's. We are facing the below issue while calling the @Transaction method(here saveAll method) from another programmatic transaction-related code.

Stack Trace:

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; 

nested exception is 
java.lang.IllegalStateException:Already value [org.springframework.jdbc.datasource.ConnectionHolder@303ef11] for key [HikariDataSource (HikariPool-1)] bound to thread [http-nio-8091-exec-3]

Example Code Snippet:

OneServiceImpl: Here we are using jdbcTemplate to save data and using programmatic transactions. From the programmatic transaction method, we are calling another serviceImpl class method which is using JPA.

public CommonResponse saveCaseConfigurations(List<CaseDTO> caseList){
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        try {
                           scheduleServiceRepo.saveCases(caseList)); //Using JDBC template
                           ......
                           serviceTwo.updateCaseLogs(caseLogs); // calling secod service method.

                            
                        } catch (Exception ex) {
                            status.setRollbackOnly();
                            throw new CustomRunTimeException("Error due to"+ex.getMessage());
                        }

                    }
                });
}

TwoServiceImpl: Here we are using Jpa and saveAll method have @Transactional annotation.

@Override
public CommonResponse updateCaseLogs(List<CaseLogs> caseLogs) {
    caseLogs = caseLogMasterRepo.saveAll(caseLogs);//Using JPA to save all in CaseLogs entity, failing here as saveAll is having @Transactional annotion.
    return new CommonResponse("SUCCESS", null,HttpStatus.OK);
}

We are using two transaction managers for two transactions. Please help me how we can disable the inner transaction and carry the same transaction to the saveAll method call.

Chirag
  • 555
  • 1
  • 5
  • 20
Raghu
  • 1
  • 1
  • 2

1 Answers1

0

Have to add required propagation levels to your JPA transaction. See below post which has all JPA transaction propagation levels in details. Propagation level set to REQUIRED to execute multiple transaction in single scope.

Spring JPA transaction over multiple methods

Krishna
  • 393
  • 2
  • 3
  • 18
  • I have tried all the propagation levels, but no luck as saveAll method is trying to create a new transaction and it is using a different datasource/transaction manager it's raising an exception. In the first server, we have programmatic transactions and in the second service, we have annotation basesd. – Raghu May 13 '21 at 13:58