Exception Handling

Because Spring advocates using runtime exceptions rather than checked exceptions, you need a mechanism to translate the checked SQLException into a runtime Spring JDBC exception. Because Spring's SQL exceptions are runtime exceptions, they can be much more granular than checked exceptions.[1]

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-11.

Listing 8-11: Custom SQLExceptionTranslator

image from book
public class MySQLErrorCodesTransalator      extends SQLErrorCodeSQLExceptionTranslator {     protected DataAccessException customTranslate(String task,          String sql, SQLException sqlex) {         if (sqlex.getErrorCode() == -12345)             return new DeadlockLoserDataAccessException(task, sqlex);         return null;     } }      // another class file, another method:      JdbcTemplate jt = new JdbcTemplate(); jt.setDataSource(dataSource); // create a custom translator and set the datasource ¿ // for the default translation lookup MySQLErrorCodesTransalator tr = new MySQLErrorCodesTransalator(); tr.setDataSource(dataSource); jt.setExceptionTranslator(tr); // use the JdbcTemplate for this SqlUpdate SqlUpdate su = new SqlUpdate(); su.setJdbcTemplate(jt); su.setSql("update orders set shipping_charge = shipping_charge * 1.05"); su.compile(); su.update();
image from book

Obviously, nothing can stop you from creating the SQLExceptionTranslator as a Spring- managed bean and using the JdbcTemplate bean in your DAO classes. Don't worry if you don't remember reading about the JdbcTemplate class, we are going now going to discuss it in more detail.

[1] 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.

Pro Spring
Pro Spring
ISBN: 1590594614
EAN: 2147483647
Year: 2006
Pages: 189

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net