MyBatis - connection to MySQL randomly dropping
*UPDATE: I found a method which didn't close the session after openning. I think this might be the cause. Will test and report later. *
We are using MyBatis with our GWT Java web application. The problem is that sometimes an exception happens while trying to read or write to the database with MyBatis. What could be the cause? Any subsequent queries will work. It seems like the connection is timed out and needs to be refreshed. This happens sometimes through the day, we don't see any pattern in this. We tried different configurations to no avail.
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.
The MyBatis configuration file:
<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>
Update 1 The exception is thrown in different "DAOs", it's not specific to a single method/call. A general method might look like this:
@Override
p开发者_JAVA百科ublic 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();
}
}
}
Where the session factory class consists of:
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.");
}
Problem solved for me. I went though all the methods that were opening a session and one session was not being closed - coding error. Thus the connection pool ran out of free connection sometimes.
精彩评论