why we need to close resources in finally block? In hibernate who takes the responsibility of closing the resourecs resultset,statement,connection?
2 Answers
Firsty, read this Why do I need to use finally to close resources?
In JDBC there are several kinds of resources that ideally should be closed after use. Even though every Statement and PreparedStatement is specified to be implicitly closed when the Connection object is closed, you can’t be guaranteed when (or if) this happens, especially if it’s used with connection pooling. You should explicitly close your Statement and PreparedStatement objects to be sure. ResultSet objects might also be an issue, but as they are guaranteed to be closed when the corresponding Statement/PreparedStatement object is closed, you can usually disregard it.
In Hibernate, obviously the internal implementation takes care of creating and closing resources. If you want know more you can always read the source code of Hibernate.
Summary: Always close PreparedStatement/Statement and Connection. Before Java 7, it was recommended to close resources in finally block since finally block always executes regardless of exception in try block.However, with Java 7+ you’d use the try-with-resources idiom to make it happen automatically.

- 2,248
- 1
- 13
- 32
The process of closing a statement is taken care of by org.hibernate.resource.jdbc.ResourceRegistry
. It's implementation is org.hibernate.resource.jdbc.internal.ResourceRegistryStandardImpl
. There's a method release
which takes in a Statement. Firstly, all the ResultSet
objects are closed and then the statement is closed finally. Below are some fragments of that:
@Override
public void release(Statement statement) {
:
:
final Set<ResultSet> resultSets = xref.get( statement );
if ( resultSets != null ) {
closeAll( resultSets );
}
xref.remove( statement );
}
close( statement );
}
P.S:
Dependency Information
compile 'org.hibernate:hibernate-core:5.2.2.Final'

- 3,409
- 3
- 29
- 52