java - Hibernate 在 24 小时左右后抛出 JDBC 异常。使用 MYSQL/hibernate

标签 java mysql hibernate

服务器启动 24 小时左右后,hibernate 抛出 JDBCConnection 异常。我正在使用 Hibernate/Mysql/Rest java 项目

hibernate .cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/DB</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">false</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="cache.use_second_level_cache">true</property>
    <property name="cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>


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

</session-factory>

我创建了 Hibernate 模板类,它用于 Hibernate 操作,如下所示

public class HibernateTemplate {
private static final Logger logger =    Logger.getLogger(HibernateTemplate.class);

static SessionFactory factory = null;
private Session session = null;
private Transaction txn = null;

public Session getSession() {
    try {
        if (session == null || !session.isOpen()) {
            session = factory.openSession();
            txn = session.beginTransaction();
        }
    } catch (JDBCConnectionException e) {

        logger.error("JDBC Connection Exception   " + e.getStackTrace());

    }
    return session;
}

public HibernateTemplate() {
    if (factory == null || factory.isClosed()) {
        factory = new Configuration().configure().buildSessionFactory();

    }
    getSession();
}

private void postAction() {
    txn.commit();
}

private void postSession() {
    if (session.isOpen())
        session.close();

}

public Object get(Criteria cr) {
    Object responseEntity = null;
    getSession();

    try {
        responseEntity = cr.list();
        smsSent = false;
    } catch (JDBCConnectionException e) {
        logger.error("JDBC Connection Exception   " + e.getStackTrace());


    } catch (Exception ex) {
        logger.error("Exception while fetching data using Hibernate Template " + ex);
        return "error";
    } finally {
        // postAction();
        postSession();
    }

    return responseEntity;
}
}

这让我很烦恼

最佳答案

在交给应用程序使用之前,在连接池中长时间闲置的连接经常会出现问题。大多数连接池都有控制连接验证的配置。您可能希望配置 c3po 以在将连接提供给您的应用程序之前测试连接。如果它发现连接不好,它会在内部处理这个异常,你就不用去处理了。开启这个的缺点是有一个额外的数据库往返,所以从连接池获取连接需要更长的时间。

您可能希望使用 testConnectionOnCheckout 而不是 idleConnectionTestPeriod(您可能正在使用它)。

引自http://www.mchange.com/projects/c3p0/#configuring_connection_testing

Configuring Connection Testing

c3p0 can be configured to test the Connections that it pools in a variety of ways, to minimize the likelihood that your application will see broken or "stale" Connections. Pooled Connections can go bad for a variety of reasons -- some JDBC drivers intentionally "time-out" long-lasting database Connections; back-end databases or networks sometimes go down "stranding" pooled Connections; and Connections can simply become corrupted over time and use due to resource leaks, driver bugs, or other causes.

c3p0 provides users a great deal of flexibility in testing Connections, via the following configuration parameters:

  • automaticTestTable
  • connectionTesterClassName
  • idleConnectionTestPeriod
  • preferredTestQuery
  • testConnectionOnCheckin
  • testConnectionOnCheckout

idleConnectionTestPeriod, testConnectionOnCheckout, and testConnectionOnCheckin control when Connections will be tested. automaticTestTable, connectionTesterClassName, and preferredTestQuery control how they will be tested.

When configuring Connection testing, first try to minimize the cost of each test. If you are using a JDBC driver that you are certain supports the new(ish) jdbc4 API — and if you are using c3p0-0.9.5 or higher! — let your driver handle this for you. jdbc4 Connections include a method called isValid() that should be implemented as a fast, reliable Connection test. By default, c3p0 will use that method if it is present.

However, if your driver does not support this new-ish API, c3p0's default behavior is to test Connections by calling the getTables() method on a Connection's associated DatabaseMetaData object. This has the advantage of being very robust and working with any database, regardless of the database schema. However, a call to DatabaseMetaData.getTables() is often much slower than a simple database query, and using this test may significantly impair your pool's performance.

The simplest way to speed up Connection testing under a JDBC 3 driver (or a pre-0.9.5 version of c3p0) is to define a test query with the preferredTestQuery parameter. Be careful, however. Setting preferredTestQuery will lead to errors as Connection tests fail if the query target table does not exist in your database prior to initialization of your DataSource. Depending on your database and JDBC driver, a table-independent query like SELECT 1 may (or may not) be sufficient to verify the Connection. If a table-independent query is not sufficient, instead of preferredTestQuery, you can set the parameter automaticTestTable. Using the name you provide, c3p0 will create an empty table, and make a simple query against it to test the database.

The most reliable time to test Connections is on check-out. But this is also the most costly choice from a client-performance perspective. Most applications should work quite reliably using a combination of idleConnectionTestPeriod and testConnectionOnCheckin. Both the idle test and the check-in test are performed asynchronously, which can lead to better performance, both perceived and actual.

For some applications, high performance is more important than the risk of an occasional database exception. In its default configuration, c3p0 does no Connection testing at all. Setting a fairly long idleConnectionTestPeriod, and not testing on checkout and check-in at all is an excellent, high-performance approach.

关于java - Hibernate 在 24 小时左右后抛出 JDBC 异常。使用 MYSQL/hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33831335/

相关文章:

java - 如何启动 Jetty Embedded 作为 Jenkins 构建的一部分

android - 如何在 RecyclerView 中显示多个项目类型?

java - 基于带有 Jersey 的服务器主机的 Hibernate 持久性上下文

java - Spring MVC Controller 响应作为静态内容缓存在浏览器中

java - Java 中的大错误或与简单运算符不一致

java - @OneToOne 与 Hibernate 共享主键用户 - 帐户的映射

Java:TableModel 和 TreeModel 的服务器端持久存储解决方案?

php - 提交到MySQL,但if语句导致问题

java - JPA with Hibernate - 如果实现复合键则缺少列

java - 无法在 Hibernate 中运行一段时间的 SQL 查询