混合jpa和jdbc集成测试时Connection第二次执行sql时被关闭原因及解决方案

阅读更多

在继承AbstractTransactionalJUnit4SpringContextTests 并使用如下代码进行集成测试时:

 

    @Before
    public void setUp() {
        setSqlScriptEncoding("utf-8");
        executeSqlScript("classpath:sql/intergration-test-data.sql", false);
    }

 可能得到如下异常:

写道
20:53:42.375 [main] WARN o.s.j.support.SQLErrorCodesFactory - Error while extracting database product name - falling back to empty error codes
org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: Couldn't perform the operation getMetaData: You can't perform a getMetaData operation after the connection has been closed

 

写道

org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQLException for SQL [delete from `sys_job`]; SQL state [null]; error code [0]; Couldn't perform the operation createStatement: You can't perform a createStatement operation after the connection has been closed; nested exception is java.sql.SQLException: Couldn't perform the operation createStatement: You can't perform a createStatement operation after the connection has been closed
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.Jdb

 

这是因为内部的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代理之:

 


        
            
                
                
                
                

                
                
                
                
                
                
            
        
    

 

 

此时在调用DataSources.doGetConnection获取ConnectionHolder时,内部使用SimpleConnectionHandle而非HibernateConnectionHandle,即releaseConnection并没有释放连接:

        public void releaseConnection(Connection con) {
 	}

 即此时并没有真正关闭实际的连接。 

 

即谁打开的连接谁负责关闭。

你可能感兴趣的:(混合jpa和jdbc集成测试时Connection第二次执行sql时被关闭原因及解决方案)