2011-06-15 106 views
2

* 更新:我发现一个方法,打开后没有关闭会话。我认为这可能是原因。稍后将进行测试和报告。 *MyBatis - 连接MySQL随机丢弃

我们正在使用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."); 
} 
+1

你能提供触发异常的代码吗? – Waldheinz 2011-06-15 10:16:35

+0

您是否尝试过使用除内置MyBatis连接池之外的连接池? – 2011-06-15 10:24:17

+0

Waldheinz - 我更新了这个问题。菲尔 - 不,我们没有。可以在配置.xml中配置吗?我在MyBatis指南中没有找到关于此的更多信息。 – 2011-06-15 11:37:00

回答

2

问题解决了我。尽管所有打开会话和一个会话的方法都没有关闭 - 编码错误。因此,连接池有时会耗尽空闲连接。