I'm developing an Struts2-Hibernate dynamic web-based application, which makes the connection with database. As during establishing the connection, most of time I forgot to close the connection.So there is any way that I can achieve this with try-catch-resource. I have also gone through the javaDoc, but it raised my confusion. This is what I got from JavaDoc, please correct me if I'm wrong.
Class which is having the connection code must implement AutoCloseable. This gives one method public void close() throws Exception
. Now my question is what code to write in close method and how to make use of Connection class which implements AutoCloseable.
MyConnectionClass
public class StuHibernateUtils implements AutoCloseable {
static SessionFactory sessionfactory;
static
{
Configuration cfg=new Configuration().configure("/student.cfg.xml");
ServiceRegistry registry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionfactory=cfg.buildSessionFactory(registry);
}
public static SessionFactory getSessionFactory()
{
return sessionfactory;
}
public static Session getSession()
{
return sessionfactory.openSession();
}
@Override
public void close() throws Exception {
// TODO Auto-generated method stub
}
}
How to use an instance of StuHibernateUtils for automatically closing the connection.
In Java 7, a new try-with-resources approach is introduced, it helps to close resources automatically. try(open resources, one or more resources){ //... } //after try block, the resource will be closed automatically.
In try-with-resources syntax, you declare and instantiate your Connection , PreparedStatement , and ResultSet in parentheses, before the braces. See Tutorial by Oracle. While your ResultSet is not being explicitly closed in your last code example, it should be closed indirectly when its statement is closed.
In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
I think you should be looking to make Session AutoCloseable rather than your helper class?
Having run into the fact that Hibernate doesn't seem to support AutoCloseable yet I'm assuming that you currently have code along the lines of:
Session session = null;
try {
session = sessionFactory.openSession();
...
} finally {
if (session!=null) session.close()
}
are you looking to do the following so you don't forget to close the session?
try (Session session = sessionFactory.openSession()) {
...
}
In my project I've created a CloseableSession which implements AutoCloseable and provides access to an underlying Session. Unfortunately, as AutoClosable and Session both have close() methods I couldn't implement both and use a normal delegation pattern.
public class CloseableSession implements AutoCloseable {
private final Session session;
public CloseableSession(Session session) {
this.session = session;
}
public Session delegate() {
return session;
}
@Override
public void close() {
session.close();
}
}
Which means you can then do the following and the session gets automatically closed.
try (CloseableSession session = new CloseableSession(
sessionFactory.openSession())) {
...
}
Although this does mean that whenever you want to use the session you now have to call session.delegate().foo().
As an aside, using a static methods to provide your session may seem like time saver but static methods generally cause problems down the line for unit testing etc and they make it harder to swap out your current implementation with another implementation. I would recommend passing in the SessionFactory or your StuHibernateUtils class where ever it is required.
For future readers, the following code is valid in Hibernate 5.4.X
public class MyClassDAO {
public void methodX(){
try(Session session = HibernateUtil.getSessionJavaConfigFactory().openSession()){
//code here
}
}
}
in case an exception is generated, the session.close () method will be called
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