Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring's JdbcTemplate close the connection if an exception is thrown?

When Spring catches an SQLException, does it close the prepared statement, result set, and/or connection before throwing it's own DataAccessException (runtime) exception?

I have a developer who wants to create an AOP aspect to catch these exceptions and log and/or close the connection.

@AfterThrowing(pointcut="dataAccessOperation()", throwing="exception")
public void doRecoveryActions(JoinPoint thisJoinPoint, DataAccessException exception) {
     // log and/or close connection
}
like image 381
aakoch Avatar asked Feb 23 '11 20:02

aakoch


People also ask

Does spring JdbcTemplate close connection?

In short yes it does close the connection.

How does JDBC handle exceptions in spring?

you need not handle any database-related exceptions explicitly instead spring jdbc framework will handle it for you. all the exceptions thrown by the spring jdbc framework are subclasses of dataaccessexception which is a type of runtimeexception, so you need not handle it explicitly.

Does JdbcTemplate use connection pooling?

Spring Example JDBC Database Connection Pool JdbcTemplate requires a DataSource which is javax. sql. DataSource implementation and you can get this directly using spring bean configuration or by using JNDI if you are using the J2EE web server or application server for managing Connection Pool.

Do we need to close connection in spring boot?

If you look inside the source, you will see every execute or query closes it resultSet and connection so you do not need to manually close them.


1 Answers

Yes.

That's the whole point of JdbcTemplate - it handles all kinds of boilerplate actions including release of all resources. See 12. Data access with JDBC.

like image 180
axtavt Avatar answered Oct 24 '22 05:10

axtavt