我有一个在 Apache TomEE 7.0.4(eclipselink 2.6.4) 上运行的持久单元,但升级到 TomEE 7.1.0(eclipselink 2.7.4) 后,JPA 调用在一段时间后失败。 persistence.xml 是:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="xxxPU" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jta-data-source>xxxDB</jta-data-source>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql"/>
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
</properties>
</persistence-unit>
</persistence>
tomee.xml中定义的数据源是
<Resource id="xxxDB" type="javax.sql.DataSource">
UserName = xxxx
Password = yyyy
JdbcDriver = com.mysql.jdbc.Driver
JdbcUrl = jdbc:mysql://localhost/dbname
JtaManaged = true
factory = org.apache.tomcat.jdbc.pool.DataSourceFactory
ConnectionProperties = autoReconnect=true;autoReconnectForPools=true;zeroDateTimeBehavior=convertToNull;useUnicode=yes;characterEncoding=UTF-8;useSSL=false
defaultAutoCommit = false
testOnBorrow = true
validationQuery = SELECT 1
validationInterval = 30000
</Resource>
一段时间后发生故障,日志如下:
15-May-2019 19:12:49.236 SEVERE [ajp-nio-8009-exec-10] org.apache.openejb.core.transaction.EjbTransactionUtil.handleSystemException EjbTransactionUtil.handleSystemException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
Error Code: 0
表面上mysql连接已关闭,但实际上并没有。我有一个 servlet,当 HTTP GET 时,证明数据源正常:
@Resource(name=xxxDB)
DataSource dataSource;
....
try (Connection connection = dataSource.getConnection()) {
// do a query to prove connection OK
}
我有一个 cron 作业,每小时获取这个 servlet。即使 JPA 抛出 com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException 之后连接也正常
我的环境Java 8、TomEE 7.1.0、Eclipselink 2.7.3
最佳答案
问题出在 Eclipselink 2.7 上。我已将这些参数添加到数据源:
testOnBorrow = true
testWhileIdle = true
timeBetweenEvictionRuns = 60000 millisecond
testOnReturn = true
validationQuery = SELECT 1
validationInterval = 30000
由于与 apache-tomee-plume 的关闭连接而失败,但对于 apache-tomee-plus 则正常。两者都是 7.1.0 版本,只是“plus”使用 openjpa,而羽流使用 eclipselink。
关于java - 持久性单元提示数据源已关闭,即使它没有关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148740/