Skip to content

Allow to configure the SQLExceptionTranslator on MyBatisExceptionTranslator #401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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