Hello!

I study Spring and the documentation says that all @Repository class exceptions will be automatically translated to a DataAccessException.

User Repository:

package org.example.dao; public interface UserDAO { void addUser(User user); } @Repository public class UserDAOImpl implements UserDAO { public void addUser(User user) { throw new HibernateException("unchecked exception"); } } 

Service for User:

 package org.example.services; public interface UserService { void addUser(User user); } @Service public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO; @Override public void addUser(User user) { try { userDAO.addUser(user); } catch (Exception e) { e.printStackTrace(); } } } 

In web.xml:

 <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> 

In fact, I get a HibernateException. I do not understand how exceptions broadcast works. Why did not HibernateException be translated into an exception of type DataAccessException?

Who can tell me what I understood wrong? :)

  • Well, maybe because DataAccessException is below HibernateException , and you catch Exception that DataAccessException - and you explicitly specify the HibernateException error. - And
  • @And, I do not quite understand something. And then what is the meaning of the broadcast? As I understand it, Spring should throw exceptions from the Repository into some kind of DataAccessException hierarchy exception. Apparently, I got it wrong. Do not tell me how it really works? - iGreetYou
  • Try catching a DataAccessException . - And
  • @And, how do I catch a DataAccessException if a HibernateException is in a different hierarchy at all? Exception will catch any (including and broadcast) exception. It seems we did not understand each other. My question is that HibernateException is not translated to a DataAccessException hierarchy exception. And I can not understand how it works. - iGreetYou
  • The code shows: HibernateException extends RuntimeException . and DataAccessException extends NestedRuntimeException , and already NestedRuntimeException extends RuntimeException , and RuntimeException extends Exception . - And

1 answer 1

It turned out that I had missed the main detail: to specify in the configs the implementation of the exception org.springframework.dao.support.PersistenceExceptionTranslator .

Summary:

  1. Configure exception translator org.springframework.dao.support.PersistenceExceptionTranslator
  2. Mark class @Repository
  3. Do not catch exceptions in the DAO itself.

Thanks to all!