Prevent Transaction to be rolled back even if the Stored Procedure invocation fails

Viewed 29

I have a service class marked with @Transactional. after saving the entities I invoke a Stored Procedure with ApplicationEventPublisher. The Listener is annotated with @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT). Now the event listener throws an exception while invoking the Stored Procedure, and it rollbacks the entire transaction. Is there a way to prevent this rollback from happening?

I need to execute the entity saving and stored procedure in the same transaction. How can this be achieved?

My Service Class Method, I need this service class method to commit the transaction, even if the stored proc execution fails. When I don't invoke the SP its works as expected.

@Transactional
void saveAndInvokeSP() {
   repo.save(entity);
   applicationEventPublisher.publishEvent(new SPInvocationEvent());
}

My Event Listener Class

class EventListener {

    final EntityManager entityManager;

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void handleCustom(SPInvocationEvent event) {
        entityManager.flush();
        invokeStoreProcedure(OUTBOUND_STORED_PROC, event);
    }

    void invokeStoreProcedure(String outProcName, SPInvocationEvent event) {
        StoredProcedureQuery outsumSP = entityManager.createStoredProcedureQuery(outProcName);
            
        try {          
            outsumSP.execute();             
        } catch (Exception e) {
           log.error(e.getMessage());
        }
    }
}
0 Answers
Related