should close connection or close session?

raj chopra

Ranch Hand

Posts: 64

posted 4 years ago

Hii All,

my project uses jdbc and hibernate while executing queries. most of time connections,session,resultsets and prepared statements,callable statements were not closed.
This leads lo resource management issues and i tend to close the connections. so i added the try catch finally block and modified the code to close the connections

In this regard i have a dialama in closing the connections or the sessions? which would be better and safe practise?

Assuming it's web app, this Session (HttpSession) will get invalidated when the user logs out or when the app idles too long and timeout. Closing such session after each database transaction can have what effect on your app?

Seems to me what would be better (in the normal sort of application) would be to tell Hibernate where your connection pool is, and let Hibernate manage that. Then use Hibernate transactions to manage your database transactions, and use Hibernate sessions according to one of the preferred ways described in the Hibernate documentation.

Trying to manage your own database connections seems to me to be a recipe for confusion, and indeed that seems to be what is happening.

raj chopra

Ranch Hand

Posts: 64

posted 4 years ago

Thanks for your reply Tsang,

Yes my project is web application. i am not sure on the effets of closing session in my app, because the code is inconsistent . on few areas code involved hibernate sessions and few orther areas with simple jdbc connections.on trial and error basis i closed few connections last time and cross cheked in tomcat server cmd prompt. it was ok on few classes, and connection closed out exception was result on orther class files.

with your suggestions i prefer to close the connection, as my primary idea is to close the database connection once the query is performed.

It is unusual to use both JDBC and Hibernate together in different classes. I suggest you use Hibernate or JDBC throughout. If using Hibernate, like Paul said let the Hibernate code handle the connection pool and stuff. If JDBC you should close the connection after each call.