Tinazhou 2013-05-03
在继承AbstractTransactionalJUnit4SpringContextTests 并使用如下代码进行集成测试时:
@Before public void setUp() { setSqlScriptEncoding("utf-8"); executeSqlScript("classpath:sql/intergration-test-data.sql", false); }
可能得到如下异常:
这是因为内部的JdbcTemplate在调用DataSourceUtils.releaseConnection(con, getDataSource());释放连接时,是调用的:org.springframework.orm.jpa.vendor.HibernateJpaDialect的HibernateConnectionHandle
public void releaseConnection(Connection con) { JdbcUtils.closeConnection(con); }
public static void closeConnection(Connection con) { if (con != null) { try { con.close(); } catch (SQLException ex) { logger.debug("Could not close JDBC Connection", ex); } catch (Throwable ex) { // We don't trust the JDBC driver: It might throw RuntimeException or Error. logger.debug("Unexpected exception on closing JDBC Connection", ex); } } }
即con.close();直接关闭连接。
此时我们应该使用TransactionAwareDataSourceProxy代理之:
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"> <property name="targetDataSource"> <bean class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver" value="${connection.driver_class}"/> <property name="driverUrl" value="${connection.url}"/> <property name="user" value="${connection.username}"/> <property name="password" value="${connection.password}"/> <property name="alias" value="${proxool.alias}"/> <property name="trace" value="${proxool.trace}"/> <property name="maximumConnectionCount" value="${proxool.maximum.connection.count}"/> <property name="minimumConnectionCount" value="${proxool.minimum.connection.count}"/> <property name="statistics" value="${proxool.statistics}"/> <property name="simultaneousBuildThrottle" value="${proxool.simultaneous.build.throttle}"/> </bean> </property> </bean>
此时在调用DataSources.doGetConnection获取ConnectionHolder时,内部使用SimpleConnectionHandle而非HibernateConnectionHandle,即releaseConnection并没有释放连接:
public void releaseConnection(Connection con) { }
即此时并没有真正关闭实际的连接。
即谁打开的连接谁负责关闭。