Skip to content

Commit

Permalink
Allow to configure the SQLExceptionTranslator on MyBatisExceptionTran…
Browse files Browse the repository at this point in the history
…slator

Fixes gh-400
  • Loading branch information
kazuki43zoo committed Sep 9, 2019
1 parent 9600ed8 commit 81efd34
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/main/java/org/mybatis/spring/MyBatisExceptionTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.mybatis.spring;

import java.sql.SQLException;
import java.util.function.Supplier;

import javax.sql.DataSource;

Expand All @@ -37,12 +38,11 @@
*/
public class MyBatisExceptionTranslator implements PersistenceExceptionTranslator {

private final DataSource dataSource;

private final Supplier<SQLExceptionTranslator> exceptionTranslatorSupplier;
private SQLExceptionTranslator exceptionTranslator;

/**
* Creates a new {@code DataAccessExceptionTranslator} instance.
* Creates a new {@code PersistenceExceptionTranslator} instance with {@code SQLErrorCodeSQLExceptionTranslator}.
*
* @param dataSource
* DataSource to use to find metadata and establish which error codes are usable.
Expand All @@ -51,8 +51,22 @@ public class MyBatisExceptionTranslator implements PersistenceExceptionTranslato
* exceptions.
*/
public MyBatisExceptionTranslator(DataSource dataSource, boolean exceptionTranslatorLazyInit) {
this.dataSource = dataSource;
this(() -> new SQLErrorCodeSQLExceptionTranslator(dataSource), exceptionTranslatorLazyInit);
}

/**
* Creates a new {@code PersistenceExceptionTranslator} instance with specified {@code SQLExceptionTranslator}.
*
* @param exceptionTranslatorSupplier
* Supplier for creating a {@code SQLExceptionTranslator} instance
* @param exceptionTranslatorLazyInit
* if true, the translator instantiates internal stuff only the first time will have the need to translate
* exceptions.
* @since 2.0.3
*/
public MyBatisExceptionTranslator(Supplier<SQLExceptionTranslator> exceptionTranslatorSupplier,
boolean exceptionTranslatorLazyInit) {
this.exceptionTranslatorSupplier = exceptionTranslatorSupplier;
if (!exceptionTranslatorLazyInit) {
this.initExceptionTranslator();
}
Expand Down Expand Up @@ -85,7 +99,7 @@ public DataAccessException translateExceptionIfPossible(RuntimeException e) {
*/
private synchronized void initExceptionTranslator() {
if (this.exceptionTranslator == null) {
this.exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(this.dataSource);
this.exceptionTranslator = exceptionTranslatorSupplier.get();
}
}

Expand Down

0 comments on commit 81efd34

Please sign in to comment.