如何利用try-catch和资源语句来关闭连接

Ric*_*cky 4 hibernate try-catch

我正在开发一个Struts2-Hibernate动态基于Web的应用程序,它与数据库建立连接.在建立连接时,大部分时间我忘记关闭连接.所以我可以用try-catch-resource实现这一点.我也经历了javaDoc,但它引起了我的困惑.这是我从JavaDoc获得的,如果我错了,请纠正我.

具有连接代码的类必须实现AutoCloseable.这给出了一种方法public void close() throws Exception.现在我的问题是用close方法编写的代码以及如何使用实现AutoCloseable的Connection类.

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

    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用StuHibernateUtils实例自动关闭连接.

Mil*_*age 11

我认为你应该寻找Session AutoCloseable而不是你的助手类?

遇到Hibernate似乎不支持AutoCloseable这一事实但我假设您目前有以下代码:

Session session = null;

try {
    session = sessionFactory.openSession();
    ...
} finally {
   if (session!=null) session.close()
}
Run Code Online (Sandbox Code Playgroud)

你想要做以下事情,所以你不要忘记关闭会议?

try (Session session = sessionFactory.openSession()) {
...
}
Run Code Online (Sandbox Code Playgroud)

在我的项目中,我创建了一个CloseableSession,它实现了AutoCloseable并提供了对底层Session的访问.不幸的是,由于AutoClosable和Session都有close()方法,我无法实现这两种方法并使用正常的委托模式.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这意味着您可以执行以下操作,会话将自动关闭.

try (CloseableSession session = new CloseableSession(
                sessionFactory.openSession())) {
...
}
Run Code Online (Sandbox Code Playgroud)

虽然这确实意味着无论何时您想要使用会话,您现在都必须调用session.delegate().foo().

顺便说一下,使用静态方法来提供会话可能看起来节省时间,但静态方法通常会导致单元测试等问题,并且它们使得将当前实现与其他实现交换变得更加困难.我建议传递SessionFactory或StuHibernateUtils类,只要它是必需的.