16
16
package org .mybatis .spring ;
17
17
18
18
import java .sql .SQLException ;
19
+ import java .util .function .Supplier ;
19
20
20
21
import javax .sql .DataSource ;
21
22
37
38
*/
38
39
public class MyBatisExceptionTranslator implements PersistenceExceptionTranslator {
39
40
40
- private final DataSource dataSource ;
41
-
41
+ private final Supplier <SQLExceptionTranslator > exceptionTranslatorSupplier ;
42
42
private SQLExceptionTranslator exceptionTranslator ;
43
43
44
44
/**
45
- * Creates a new {@code DataAccessExceptionTranslator } instance.
45
+ * Creates a new {@code PersistenceExceptionTranslator } instance with {@code SQLErrorCodeSQLExceptionTranslator} .
46
46
*
47
47
* @param dataSource
48
48
* DataSource to use to find metadata and establish which error codes are usable.
@@ -51,8 +51,22 @@ public class MyBatisExceptionTranslator implements PersistenceExceptionTranslato
51
51
* exceptions.
52
52
*/
53
53
public MyBatisExceptionTranslator (DataSource dataSource , boolean exceptionTranslatorLazyInit ) {
54
- this .dataSource = dataSource ;
54
+ this (() -> new SQLErrorCodeSQLExceptionTranslator (dataSource ), exceptionTranslatorLazyInit );
55
+ }
55
56
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 ;
56
70
if (!exceptionTranslatorLazyInit ) {
57
71
this .initExceptionTranslator ();
58
72
}
@@ -85,7 +99,7 @@ public DataAccessException translateExceptionIfPossible(RuntimeException e) {
85
99
*/
86
100
private synchronized void initExceptionTranslator () {
87
101
if (this .exceptionTranslator == null ) {
88
- this .exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator ( this . dataSource );
102
+ this .exceptionTranslator = exceptionTranslatorSupplier . get ( );
89
103
}
90
104
}
91
105
0 commit comments