12

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
}
aakoch
  • 1,164
  • 1
  • 9
  • 18

2 Answers2

21

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • The documentation describes translating the exceptions and it talks about closing connections, but nothing specifically states that it closes connections when catching exceptions. That's why I asked it here. – aakoch Feb 23 '11 at 22:36
  • @Adam: Yes, documentation seems to be not very verbose in this case, but `JdbcTemplate` actually takes care of closing connections in the case of exception (though when used with Spring-managed transactions connections are actually closed by transactio manager, but it doesn't matter). – axtavt Feb 24 '11 at 09:10
  • In the case of a unchecked/runtime exception, will jdbctemplate also clean up and close the connection? – tekumara Nov 15 '13 at 17:18
  • Yes - it will catch an unchecked/runtime exception and close the connection, but only if that exception is not caught higher up the stack. – tekumara Nov 15 '13 at 17:39
0

I think your developer should take a look at springs transaction managemant capabilities. You can use AOP to advice logging, rollback behavior and even retry or other exception handling actions to react completly declarative.

Community
  • 1
  • 1
zoidbeck
  • 4,091
  • 1
  • 26
  • 25