Consistent exception handling and translation

In the Spring JDBC module, Spring provides DataAccessException to handle all types of database-specific SQL error code, and generates meaningful exception classes. In the Spring ORM module, as we already know, Spring supports integration for several ORM solutions, such as Hibernate, JPA, or JDO in a DAO, and these persistence technologies provide their own native exception classes as HibernateException, PersistenceException, or JDOException depending on the technology. These native exceptions of the ORM Frameworks are unchecked exceptions, so we don't have to handle them in the application. The caller of the DAO services cannot do specific handling unless the application is strongly ORM based, or does not need any special exception treatment. Spring provides a consistent approach throughout the ORM Frameworks; you don't need to implement specific code for any ORM in a Spring application. It enables exception translation by using the @Repository annotation. If any class in the Spring application is annotated with @Repository annotation, then that class is eligible for Spring DataAccessException translation. Take for example the following code for the AccountDaoImpl class:

    @Repository 
    public class AccountDaoImpl implements AccountDao { 
      // class body here... 
    } 
 
    <beans> 
      <!-- Exception translation bean post processor --> 
      <bean class="org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor"/> <bean id="accountDao" class="com.packt.patterninspring.chapter8.
bankapp.dao.AccountDaoImpl"/> </beans>

As you can see in the preceding code, the PersistenceExceptionTranslationPostProcessor class is a bean post processor, which automatically searches for all exception translators and also advises all the registered beans annotated with the @Repository annotation in the container. It applies the discovered exception translators to those annotated beans, and these translators can intercept and apply the appropriate translation on the thrown exceptions.

Let's see some more design patterns that are implemented in the Spring ORM module to provide the best enterprise solution for the integration tier of an enterprise application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset