Skip to content

Commit 8b217af

Browse files
committed
fix for http://code.google.com/p/mybatis/issues/detail?id=237 . ensure the connection is left closed in case of error.
1 parent 283fe70 commit 8b217af

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSessionFactory.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,12 @@ public Configuration getConfiguration() {
6565
}
6666

6767
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
68+
Connection connection = null;
6869
try {
6970
final Environment environment = configuration.getEnvironment();
7071
final DataSource dataSource = getDataSourceFromEnvironment(environment);
7172
TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
72-
Connection connection = dataSource.getConnection();
73+
connection = dataSource.getConnection();
7374
if (level != null) {
7475
connection.setTransactionIsolation(level.getLevel());
7576
}
@@ -78,6 +79,7 @@ private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionI
7879
Executor executor = configuration.newExecutor(tx, execType);
7980
return new DefaultSqlSession(configuration, executor, autoCommit);
8081
} catch (SQLException e) {
82+
closeConnection(connection);
8183
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
8284
} finally {
8385
ErrorContext.instance().reset();
@@ -129,5 +131,15 @@ private Connection wrapConnection(Connection connection) {
129131
}
130132
}
131133

134+
private void closeConnection(Connection connection) {
135+
if (connection != null) {
136+
try {
137+
connection.close();
138+
} catch (SQLException e1) {
139+
// Intentionally ignore. Prefer previous error.
140+
}
141+
}
142+
}
143+
132144
}
133145

0 commit comments

Comments
 (0)