You should maintain your session as long as you want to be connected to your database.
But sessions are not a thread safe objects and cannot be shared by multiple threads. So you should use one session per request.
So bottomline is, if you're using a single threaded application, then it's better to use one session for your entire application. You can use SessionFactory.getCurrentSession()
for this.
But if your application is shared across multiple threads, then you should always open new sessions using SessionFactory.openSession()
. Although this is slower than the former, but it's thread safe.
Do you know where could it be handled
The best practice is to close them in finally
block. However if you're using Java SE 7 and later, then you can handle them in try-with-resources
as well.