*更新:我发现了一个打开后没有关闭会话的方法。我想这可能是原因。稍后会测试并报告。*
我们将 MyBatis 与 GWT Java Web 应用程序一起使用。问题是有时在尝试使用 MyBatis 读取或写入数据库时会发生异常。可能是什么原因?任何后续查询都将起作用。似乎连接已超时,需要刷新。这种情况有时会在一天中发生,我们看不到任何模式。我们尝试了不同的配置无济于事。
org.apache.ibatis.exceptions.PersistenceException:
### Error opening session. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communications link failure during rollback(). Transaction resolution unknown.
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communications link failure during rollback(). Transaction resolution unknown.
MyBatis 配置文件:
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/project"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
<property name="poolMaximumActiveConnections" value="20"/>
<property name="poolMaximumIdleConnections" value="5"/>
<property name="poolPingEnabled" value="true"/>
<property name="poolPingQuery" value="select 1"/>
</dataSource>
</environment>
</environments>
更新 1 异常在不同的“DAO”中引发,它不特定于单个方法/调用。一般的方法可能如下所示:
@Override
public Entity get(String id) throws Exception {
LogHelper.logMethodStart(logger, "get", "id", id);
SqlSession session = null;
try {
session = GenericDao.SESSION_FACTORY.openSession();
EntityDao mapper = session.getMapper(EntityDao.class);
return mapper.get(id);
} catch (Exception e) {
logger.error(e);
throw e;
} finally {
if (session != null) {
session.close();
}
}
}
会话工厂类包括:
public static SqlSessionFactory SESSION_FACTORY;
static {
logger.info("SqlSessionFactory init started.");
String aResource = "iBatisConfig.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader(aResource);
} catch (IOException e) {
throw new RuntimeException(e);
}
SESSION_FACTORY = new SqlSessionFactoryBuilder().build(reader);
try {
reader.close();
} catch (IOException e) {
logger.error(e);
}
SESSION_FACTORY.getConfiguration().addMappers("com.example.project.server.dao");
logger.info("SqlSessionFactory init end.");
}