【问题标题】:Hibernate not closing connection休眠不关闭连接
【发布时间】:2013-09-05 03:55:39
【问题描述】:

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

提前谢谢.....

【问题讨论】:

    标签: java mysql hibernate rest jersey


    【解决方案1】:

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

    【讨论】:

    • 因为我正在使用使用上下文会话,这就是我不关闭会话的原因
    • 我不确定,但上下文定义了 getCurrentSession() 合同和仅在提交/回滚时打开/关闭管理(我在这里看不到回滚)
    • 但我正在使用 transaction.commit();在注册完成时。您是否想说在这种情况下我必须在所有 CURD 操作的情况下使用提交?
    • 可以提交,但是回滚呢?不见了
    • 我已经检查过我从未在事务中遇到异常,所以回滚很重要,但即使我遇到问题,我仍然使用回滚..
    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2019-02-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多