休眠连接泄漏

时间:2019-04-27 18:43:39

标签: mysql hibernate c3p0

我是网络开发人员的新手,去年以来,我是一家公司的见习生,而且我遇到以下问题:

我正在使用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>

0 个答案:

没有答案