img
Spring's SQL exceptions are runtime exceptions, they can be much more granular than checked
exceptions. (By definition, this is not a feature of runtime exceptions, but it is very inconvenient to have
to declare a long list of checked exceptions in the throws clause; hence, checked exceptions tend to be
much more coarse-grained than their runtime equivalents.)
Spring provides a default implementation of the SQLExceptionTranslator interface, which takes care
of translating the generic SQL error codes into Spring JDBC exceptions. In most cases, this
implementation is sufficient enough, but we can extend Spring's default implementation and set our
new SQLExceptionTranslator implementation to be used in JdbcTemplate, as shown in Listing 8-21.
At the same time, we need to add the dependency on spring-jdbc into the project, as shown in
Table 8-4.
Table 8-4. Dependency for spring-jdbc
Group ID
Artifact ID
Version
Description
3.1.0.RELEASE
Spring JDBC module
org.springframework
spring-jdbc
Listing 8-21. Custom SQLExceptionTranslator
package com.apress.prospring3.ch8.exception.translator;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
public class MySQLErrorCodesTranslator extends
SQLErrorCodeSQLExceptionTranslator  {
protected DataAccessException customTranslate(String task,
String sql, SQLException sqlex) {
if (sqlex.getErrorCode() == -12345)
return new DeadlockLoserDataAccessException(task, sqlex);
return null;
}
}
To use the custom translator, we need to pass it into JdbcTemplate in the DAO classes. Listing 8-22
shows a sample code snippet for this purpose.
Listing 8-22. Using Custom SQLExceptionTranslator in Spring Jdbc
// Within any DAO class
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
// create a custom translator and set the datasource
// for the default translation lookup
MySQLErrorCodesTranslator errorTranslator =
new MySQLErrorCodesTranslator();
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home