首页 > 解决方案 > 休眠连接泄漏

问题描述

我是网络开发的新手,自去年以来我是一家公司的实习生,我有以下问题:

我正在使用 JSF2.3 和 Hibernate 5.4.2.Final 和 c3p0 5.4.2.Final 制作一个 Web 应用程序。问题是每次我运行并进入登录页面时,我需要检查是否有管理员用户已经注册 - 我根据员工的代码计算员工表 - 如果没有任何管理员,那么我得到国家/地区列表并呈现表格注册菜单。所以,我从我的 HibernateUtil.class 中的 sessionfactory.opensession() 获取会话,进行计数并像片段一样清除/关闭会话:

public Long retornaLong(String query) throws Exception{
            Session session = new HibernateUtil().getSession();
            try {
                return (Long) session.createQuery(query).getSingleResult();
            }finally {
                session.clear();
                session.close();
            }
        }

然后我从

@SuppressWarnings("unchecked")
    public List<T> retornaList(String query) throws Exception{
        Session session = new HibernateUtil().getSession();
        try {
            return (List<T>) session.createQuery(query).getResultList();
        }finally {
            session.clear();
            session.close();
        }
    }

但是如果我不断刷新页面(@viewscoped),比如 15 次以上,最终我会得到太多的连接异常,如果我对两个查询都使用一个会话,则不会发生这种情况。我认为会话没有足够的时间关闭,导致连接泄漏。我想为每个查询使用一个会话,有人可以帮助我吗?非常感谢。

我的 hibernate.cfg.xml

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory>

        <!-- properties -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/vetsnpets?useTimezone=true&amp;serverTimezone=UTC</property>
        <property name="hibernate.connection.username">vetsNpets</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hiberante.show_sql">false</property>
        <property name="hiberante.format_sql">false</property>
        <property name="hbm2ddl.auto">validate</property>
        <property name="current_session_context_class">thread</property>

        <!-- C3P0 -->
        <property name="hibernate.c3p0.initialPoolSize">3</property>
        <property name="hibernate.c3p0.minPoolSize">3</property>
        <property name="hibernate.c3p0.maxPoolSize">20</property>
        <property name="hibernate.c3p0.maxStatements">100</property>
        <property name="hibernate.c3p0.maxStatementsPerConnection">5</property>
        <property name="hibernate.c3p0.maxIdleTime">2700</property>
        <property name="hibernate.c3p0.maxIdleTimeExcessConnections">600</property>
        <property name="hibernate.c3p0.acquireIncrement">1</property>

标签: mysqlhibernatec3p0

解决方案


推荐阅读