Do I need to manually close a connection obtained from a hibernate session?
If I do this, will I be closing one of the connections in the connection pool?
Will hibernate automatically close the connection if I do not?
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "sql query";
try {
Session session = this.sessionFactory.getCurrentSession();
con = session.connection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
//read result set
}
} catch (SQLException exp) {
log.error("Error: ", exp);
} finally{
if(ps != null)
ps.close();
if(con != null)
con.close(); //Is this required?
}
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.
When you don't close your Hibernate sessions and therefore do not release JDBC connections, you have what is typically called Connection leak. So, after a number of requests (depending on the size of your connection pool) the server will not be able to acquire a connection to respond your request.
You must additonally close the factory. Like others have pointed above, it's not good practice to open and close sessionFactory every time you transact but rather have one sessionFactory in the app on which you open and close the sessions. Opening the sessionFactory is expensive.
If you don't close it, it leaks, and ties up server resources. @EJP The connection itself might be thread-safe (required by JDBC), but the applications use of the connection is probably not threadsafe. Think of things like different transaction isolation, boundaries (commit/rollback/autocommit) etc.
In general no you should not close that connection. The hibernate session may still want to use the same connection object for other tasks later in the life-cycle of the session that you are going to break by closing its connection. It is hibernate's job to manage the lifecycle of that connection object.
The exception is, as described in the javadoc, if you have ConnectionReleaseMode.AFTER_STATEMENT turned on and the JDBC provider supports that mode. Which is not often the case since you have to be in auto-commit mode for it to work.
Yes, you should close
the connection. If you are using a connection pool, you should disconnect the session, this will not actually close it, but it will release it back to the pool.
For non-connection pools. In the javadocs it states
Note: A Connection object is automatically closed when it is garbage collected. Certain fatal errors also close a Connection object.
However, as it will be closed, it would be better to do by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With