SQLExceptionTranslator example by R4R Team

SQLExceptionTranslator example:-

SQLExceptionTranslator is an interface to be implemented by classes that can translate between SQLExceptions and Spring’s own org.springframework.dao.DataAccessException, which is agnostic in regard to data access strategy.

It is a Strategy interface for translating between SQLExceptions and Spring's data access strategy-agnostic DataAccessException hierarchy.

SQLErrorCodeSQLExceptionTranslator is the implementation of SQLExceptionTranslator that is used by default. This implementation uses specific vendor codes. It is more precise than the SQLState implementation. The error code translations are based on codes held in a JavaBean type class called SQLErrorCodes. This class is created and populated by an SQLErrorCodesFactory which as the name suggests is a factory for creating SQLErrorCodes based on the contents of a configuration file named sql-error-codes.xml. This file is populated with vendor codes and based on the DatabaseProductName taken from the DatabaseMetaData. The codes for the actual database you are using are used.
 

import java.sql.SQLException;

import org.springframework.dao.DataAccessException;

import org.springframework.dao.DeadlockLoserDataAccessException;

import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;

public class CustomSQLErrorCodesTranslator extends

SQLErrorCodeSQLExceptionTranslator {

protected DataAccessException customTranslate(String task, String sql,

SQLException sqlex) {

if (sqlex.getErrorCode() == -12345) {

return new DeadlockLoserDataAccessException(task, sqlex);}

return null; }}

In this example, the specific error code -12345 is translated and other errors are left to be translated by the default translator implementation. 

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!