What is “persistence exception translation” for @R

2020-05-26 02:40发布

问题:

I was reading Spring with annotation part and I came across @Repositoryannotation
I read that @Repository beans differ from @Component beans in the sense that they are eligible for persistence exception translation.

Can somebody please elaborate what is meant by persistence exception translation?

回答1:

Persistence Exception Translation is the process of converting low level persistence exceptions into high level Spring exceptions.

From the SpringSource Site:

Common data access exceptions. Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.

One of the major benefits of this is that exceptions are turned into Runtime Exceptions, in effect you are not required to add the throws declaration to your methods signature.

http://static.springsource.org/spring/docs/2.5.x/reference/orm.html



回答2:

It provides a consistent exception hierarchy regardless of the database type or persistence methodology/technology you're using.

You get the same exceptions for the same types of errors regardless of whether you're using Oracle vs MySQL or JPA vs JDBC.

Take a look at the SQLErrorCodeSQLExceptionTranslator and sql-error-codes.xml.

sql-error-codes.xml is particularly interesting as you can see all the various vendor-specific error codes and what exception in the hierarchy they map to.



回答3:

The Spring exception translation mechanism can be applied transparently to all beans annotated with @Repository – by defining an exception translation bean post processor bean in the Context