Home > OS >  How to close connection at the end of method
How to close connection at the end of method

Time:03-10

Hi I wanted to ask about how to close the connection at the end of the method, while second method get called.

@Transactional(value = "transactionManagerDC")
public void Execute()
{
     // 1. select from DB - took 2 min
     ExecuteAPI()

}; 

public void ExecuteAPI()
{
  // API CALL

}; 

But the longer API call keep the transaction open and put into ideal and terminated. How to commit and close the transaction before the API call method.

CodePudding user response:

finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }

CodePudding user response:

When a transaction is declared using a @Transactional annotation it will end (commit or rollback) when the program control returns from the annotated method, either normally or when an exception occurs.

To have more control over the transactional execution, I would inject a PlatformTransactionManager and use a TransactionTemplate programatically instead of this declarative approach.

This is a fairly good tutorial on programmatic control over the transactions: https://www.baeldung.com/spring-programmatic-transaction-management


In your example, you want to end the transaction before the API call, basically after selecting your data. I'm failing to see why do need a transaction in the first place.

  • Related