Skip to content

Commit 9e6b942

Browse files
authored
Merge pull request mybatis#401 from kazuki43zoo/mybatisgh-400
Allow to configure the SQLExceptionTranslator on MyBatisExceptionTranslator
2 parents 95fba4e + 5baca30 commit 9e6b942

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/main/java/org/mybatis/spring/MyBatisExceptionTranslator.java

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package org.mybatis.spring;
1717

1818
import java.sql.SQLException;
19+
import java.util.function.Supplier;
1920

2021
import javax.sql.DataSource;
2122

@@ -37,12 +38,11 @@
3738
*/
3839
public class MyBatisExceptionTranslator implements PersistenceExceptionTranslator {
3940

40-
private final DataSource dataSource;
41-
41+
private final Supplier<SQLExceptionTranslator> exceptionTranslatorSupplier;
4242
private SQLExceptionTranslator exceptionTranslator;
4343

4444
/**
45-
* Creates a new {@code DataAccessExceptionTranslator} instance.
45+
* Creates a new {@code PersistenceExceptionTranslator} instance with {@code SQLErrorCodeSQLExceptionTranslator}.
4646
*
4747
* @param dataSource
4848
* DataSource to use to find metadata and establish which error codes are usable.
@@ -51,8 +51,22 @@ public class MyBatisExceptionTranslator implements PersistenceExceptionTranslato
5151
* exceptions.
5252
*/
5353
public MyBatisExceptionTranslator(DataSource dataSource, boolean exceptionTranslatorLazyInit) {
54-
this.dataSource = dataSource;
54+
this(() -> new SQLErrorCodeSQLExceptionTranslator(dataSource), exceptionTranslatorLazyInit);
55+
}
5556

57+
/**
58+
* Creates a new {@code PersistenceExceptionTranslator} instance with specified {@code SQLExceptionTranslator}.
59+
*
60+
* @param exceptionTranslatorSupplier
61+
* Supplier for creating a {@code SQLExceptionTranslator} instance
62+
* @param exceptionTranslatorLazyInit
63+
* if true, the translator instantiates internal stuff only the first time will have the need to translate
64+
* exceptions.
65+
* @since 2.0.3
66+
*/
67+
public MyBatisExceptionTranslator(Supplier<SQLExceptionTranslator> exceptionTranslatorSupplier,
68+
boolean exceptionTranslatorLazyInit) {
69+
this.exceptionTranslatorSupplier = exceptionTranslatorSupplier;
5670
if (!exceptionTranslatorLazyInit) {
5771
this.initExceptionTranslator();
5872
}
@@ -85,7 +99,7 @@ public DataAccessException translateExceptionIfPossible(RuntimeException e) {
8599
*/
86100
private synchronized void initExceptionTranslator() {
87101
if (this.exceptionTranslator == null) {
88-
this.exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(this.dataSource);
102+
this.exceptionTranslator = exceptionTranslatorSupplier.get();
89103
}
90104
}
91105

0 commit comments

Comments
 (0)