Accollativo
Accollativo

Reputation: 1559

Spring data jpa and JdbcTemplate - Should I close connection?

Should I close connection or Spring will handle it?

@Autowired
MyRepository myRepository;  

@Autowired
@Qualifier("myJdbc")
JdbcTemplate myJdbc;

@GetMapping("/v1/controlla-abilitazione")
public Set<String> controlloAbilitazione() {
    try {
        Connection conn = myJdbc.getDataSource().getConnection();
        //Here I use previous connection to call an oracle PL/SQL via basic oracle jdbc

        //Should I close connection?
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

(I know that I can use Spring to handle PL/SQL, but Spring doesn't have native support for Oracle Type as return from PL/SQL)

Upvotes: 0

Views: 449

Answers (1)

davidxxx
davidxxx

Reputation: 131496

Not tried but if you execute the SQL or PL/SQL query from the Connection object, you don't use Spring JDBC features for executing your query, so you should not expect that Spring closes the connection for you. It is not aware of the datasource provider activity about that.
So Connection.close() should be probably required.

It is an theory but you could check it easily enough. Store the Connection in a field of the bean and do a check at the beginning of the method.

Connection conn;
@GetMapping("/v1/controlla-abilitazione")
public Set<String> controlloAbilitazione() {
    if (conn != null && !conn.isClosed){
      throw new RuntimeException("Oh it was not closed");
    }
    try {
        conn = myJdbc.getDataSource().getConnection();           
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

Now invoke your controller once and another time. If you get the exception, you know why.

Upvotes: 1

Related Questions