4

我正在使用 Hibernate + jersey Rest And 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 层内进行事务和会话。请帮助我,我正在尝试解决这个问题,但没有得到任何解决方案,请看看上面的配置和代码有什么问题......

提前致谢.....

4

1 回答 1

1

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

于 2013-09-02T06:12:52.200 回答