如何使用try-catch和resource语句来关闭连接 [英] How to make use of try-catch and resource statement for closing the connection

查看:224
本文介绍了如何使用try-catch和resource语句来关闭连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

具有连接代码的类必须实现 AutoCloseable 。这给出了一个方法 public void close()抛出Exception 。现在我的问题是在close方法中编写什么代码,以及如何使用实现AutoCloseable的Connection类。
$ b MyConnectionClass

  public class StuHibernateUtils实现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();


$ b @Override
public void close()抛出异常{
// TODO自动生成的方法存根

}
}

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

解决方案

我认为您应该期待让Session AutoCloseable而不是您的助手类?



遇到了Hibernate似乎不支持AutoCloseable的事实,我假设您目前有以下代码:

  Session session = null; 

尝试{
session = sessionFactory.openSession();
...
} finally {
if(session!= null)session.close()
}

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

  try(Session session = sessionFactory.openSession()){
...
}

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

  public类CloseableSession实现了AutoCloseable {

private final Session session;

public CloseableSession(Session session){
this.session = session;
}

public Session delegate(){
return session;
}

@Override
public void close(){
session.close();


$ / code>

这意味着您可以执行以下操作和会话

$ p $ try(CloseableSession session = new CloseableSession(
sessionFactory.openSession())){






$ b

尽管这意味着只要你想使用你现在必须调用session.delegate()。foo()。

另外,使用静态方法来提供会话可能看起来像是节省时间但静态方法通常会导致单元测试等问题的出现,并且使得将当前的实现换成另一个实现变得更加困难。我建议在任何需要的时候传入SessionFactory或StuHibernateUtils类。


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.

解决方案

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.

这篇关于如何使用try-catch和resource语句来关闭连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆