Manish
Manish

Reputation: 1519

Why we need to translate Native Hibernate Exceptions to Spring DataAccessExceptio

I was going through @Repository Annotation and it was mentioned that it's used for translation of Exception So that Hibernate Exception to Spring DataAccessException. Also we need to configure following postprocessor

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

So My question is why this translation of Exception is required.Can't we handle Native Exception Directly ?

Thanks,

Upvotes: 1

Views: 526

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42481

I think it's done for the sake of clean separation of responsibilities.

In a nutshell, DAO is a layer that encapsulates all the work with the database, Service layer is a place to put your business logic.

If so, the knowledge about Hibernate or any other database related tool has to remain inside the DAO, and Service should know nothing about it. If you, for example, decide to switch from Hibernate to, say, Jooq, or more generally speaking decide to change Relational Database for something else, maybe NoSQL, the service layer will remain just the same, and only the DAO implementation will change.

This flexibility is a cool thing, however, Exceptions, when thrown out of DAO and reaching the Service layer can break this design, because if service has to catch Hibernate specific exceptions, is essentially coupled to Hibernate.

So, Spring "suggest" to throw much more generic "DataAccessException"

Hope this answers your question

Upvotes: 3

Related Questions