Java 休眠不关闭连接

Java 休眠不关闭连接,java,mysql,hibernate,rest,jersey,Java,Mysql,Hibernate,Rest,Jersey,我使用Hibernate+jersey Rest和Mysql作为数据库的后端。在Hibernate中,使用cp3池进行连接,但一段时间后,它会创建太多空闲连接并卡住。我的配置是: package com.appname.hibernate.util; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; pub

我使用Hibernate+jersey Rest和Mysql作为数据库的后端。在Hibernate中,使用cp3池进行连接,但一段时间后,它会创建太多空闲连接并卡住。我的配置是:


package com.appname.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static SessionFactory sessionFactory;

static {
    try {
        Configuration configuration = new Configuration().configure();

        sessionFactory = configuration.buildSessionFactory();
    } catch (HibernateException he) {
        System.err.println("Error creating Session: " + he);
        he.printStackTrace();
        throw new ExceptionInInitializerError(he);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}
////////////////////// INSIDE DAO ///////////////////////////

private Session getSession() {

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session;
try {
    session = sessionFactory.getCurrentSession();
} catch (org.hibernate.HibernateException he) {
    session = sessionFactory.openSession();
}
return session;
}

public Users regsiterUser(Users users) throws Exception {

Session session = null;

try {
session = getSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(users);
transaction.commit();
return users;

//Using context session that is why I am not closing session
} catch (Exception e) { throw e; }
}
我从控制器中调用这个DAO函数,在DAO层中进行事务和会话。请帮助我,我正试图解决这个问题,但没有得到任何解决方案,请看看上面的配置和代码有什么问题


提前感谢….

我想这个
session=sessionFactory.openSession()应该在使用后手动关闭,因为它不是由使用后释放资源的编排器管理的。

因为我使用的是上下文会话,所以我不关闭会话。我不确定这一点,但上下文仅在提交/回滚时定义getCurrentSession()协定和打开/关闭管理(我在这里看不到回滚),但我使用的是transaction.commit();在注册完成时。您想说在这种情况下,我必须在所有CURD操作中使用commit吗?对于commit,可以,但是回滚呢?missing我已经检查过,我在事务中从未遇到异常,所以回滚非常重要,但即使我面临问题,我仍然使用了rollback。。