【问题标题】:What are the required C3P0 settings for Hibernate?Hibernate 所需的 C3P0 设置是什么?
【发布时间】:2015-03-07 01:49:57
【问题描述】:

我将 Hibernate 4.3.0 与 MySQL 和 Tomcat 一起使用。所有必需的库都在类路径中,这是hibernate.cfg.xml

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="current_session_context_class">thread</property>

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.idle_test_period">300</property>

通过上述设置,在 20 次连接到数据库后,应用程序不再连接,并且我在应用程序日志中没有找到与此行为相关的信息。

有谁知道出了什么问题,以及如何正确设置 c3p0 和休眠?

【问题讨论】:

    标签: java mysql hibernate jpa c3p0


    【解决方案1】:

    设置很好。连接用完的原因是连接没有正确释放。

    确保你:

    • 成功提交事务
    • 失败时回滚事务
    • 完成后关闭 Hibernate 会话:

    因此,如果您没有 Spring 代表您处理事务/会话管理,您应该这样操作 Hibernate 会话:

    Session session = factory.openSession();
    Transaction tx = null;
    try {
       tx = session.beginTransaction();       
       ...
       tx.commit();
    }
    catch (Exception e) {
       if (tx!=null) tx.rollback(); 
    }finally {
       session.close();
    }
    

    【讨论】:

    • 据我所知,这发生在不需要事务的操作上。我将代码更改为关闭工厂(和会话对象):SessionFactory factory = HibernateUtil.getSessionFactory(); Session hSession = factory.openSession(); Criteria count = hSession.createCriteria(UserTable.class); count.setProjection(Projections.rowCount()); long total = (long) count.uniqueResult(); hSession.close(); factory.close(); 但结果与以前相同。
    • 您只需要在应用关闭时关闭会话工厂,因为它是在每次方法调用时创建的昂贵对象。试试我的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 2016-06-26
    相关资源
    最近更新 更多