From e83fa08f54be4c601d3125372bf760d8f49a3870 Mon Sep 17 00:00:00 2001 From: bernd Date: Wed, 14 Nov 2012 21:24:31 +0100 Subject: [PATCH 17/25] Add example on how to use the exception translator mechanism to use the Spring exception hierarchy. --- .../spring/SpringEoDSQLExceptionTranslator.java | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 eodsql/docs/documentation/examples/net/lemnik/eodsql/spring/SpringEoDSQLExceptionTranslator.java diff --git a/eodsql/docs/documentation/examples/net/lemnik/eodsql/spring/SpringEoDSQLExceptionTranslator.java b/eodsql/docs/documentation/examples/net/lemnik/eodsql/spring/SpringEoDSQLExceptionTranslator.java new file mode 100644 index 0000000..7692469 --- /dev/null +++ b/eodsql/docs/documentation/examples/net/lemnik/eodsql/spring/SpringEoDSQLExceptionTranslator.java @@ -0,0 +1,58 @@ +package net.lemnik.eodsql.spring; +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import net.lemnik.eodsql.EoDException; +import net.lemnik.eodsql.impl.ExceptionTranslationUtils; +import net.lemnik.eodsql.impl.ExceptionTranslator; + +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; +import org.springframework.jdbc.support.SQLExceptionTranslator; + +/** + * An {@link ExceptionTranslator} that uses the {@link SQLExceptionTranslator} underneath. + * + * @author Bernd Rinn + */ +public class SpringEoDSQLExceptionTranslator implements ExceptionTranslator +{ + /** + * Enables the translation of SQL Exceptions to their (unchecked) Spring pendants rather than + * the generic {@link EoDException}. + */ + public static void activate() + { + ExceptionTranslationUtils.setExceptionTranslator(new SpringEoDSQLExceptionTranslator()); + } + + public RuntimeException translateException(DataSource dataSource, String task, String sql, + SQLException ex) + { + return new SQLErrorCodeSQLExceptionTranslator(dataSource).translate(task, sql, ex); + } + + public RuntimeException translateException(Connection connection, String task, String sql, + SQLException ex) + { + try + { + final String databaseProductName = connection.getMetaData().getDatabaseProductName(); + return new SQLErrorCodeSQLExceptionTranslator(databaseProductName).translate(task, sql, + ex); + } catch (SQLException ex1) + { + return new SQLErrorCodeSQLExceptionTranslator().translate(task, sql, ex); + } + } + + public RuntimeException uniqueResultExpected() + { + return new IncorrectResultSizeDataAccessException( + "A unique result was expected but the database returned multiple rows.", 1); + } + +} + -- 1.8.0