问题:web app使用JPA配置persistence.xml连接MySQL做持久化,JPA使用的是Hibernate的jar包,web app在过了一夜之后不能正常工作,出现空指针异常SEVERE: Servlet.service() for servlet jsp threw exception java.lang.NullPointerException
出事的persistence.xml如下:
RootCause:
MySQL default的wait_timeout和interactive_timeout 时间为8小时,如果没有对JDBC Connection Pool设置的话,超过这个时间数据库连接池的连接就会被MySQL断开。
这里跟这个问题相关的两个参数是
wait_timeout : MySQL关闭没有活动的连接的等待时间(秒)
interactive_timeout:MySQL关闭有交互的连接的等待时间(秒)
这个情况下可以这么理解,JDBC连接池初始化了20个连接,其中15个还没有实际的交互,5个有数据库操作正在进行。
wait_timeout作用的是这15个连接,MySQL等待8小时发现这15个连接依旧没有交互的话,就关闭这些连接。
interactive_timeout作用的是5个有交互的连接,从最后一次交互结束算起MySQL等待8小时发现这5个连接没有继续有交互活动的话就关闭这个连接。
解决办法:在persistence.xml中增加配置connection pool的属性参数
c3p0是hibernate用到的开源的数据库连接池,下面是主要参数的解释
- hibernate.c3p0.min_size This is the minimum number of JDBC connections that C3P0 keeps ready at all times
- hibernate.c3p0.max_size This is the maximum number of connections in the pool. An exception is thrown at runtime if this number is exhausted.
- hibernate.c3p0.timeout You specify the timeout period (in this case, 300 seconds) after which an idle connection is removed from the pool).
- hibernate.c3p0.max_statements Maximum Number of statements that will be cached. Caching of prepared statements is essential for best performance with Hibernate.
- hibernate.c3p0.idle_test_periods This is the iddle time in seconds before a connection is automatically validated.
参考:
http://www.taobaodba.com/html/433_mysql_timeout_analyze.html
http://stackoverflow.com/questions/3123962/hibernate-and-mysql-timeout-problem-doesnt-work-with-c3p0
http://stackoverflow.com/questions/475893/which-are-the-required-c3p0-settings-for-hibernate-in-order-to-avoid-deadlocks