How to make use of try-catch and resource statement for closing the connection

六眼飞鱼酱① 提交于 2020-01-03 18:51:24

问题


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.


回答1:


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.




回答2:


This has been fixed in hibernate version 5. If you can upgrade to version 5, please use this. Supported Jira ticket

https://hibernate.atlassian.net/browse/HHH-8898



来源:https://stackoverflow.com/questions/24041170/how-to-make-use-of-try-catch-and-resource-statement-for-closing-the-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!