2017-04-20 22 views

回答

1

的自動獎獎金的答案是錯

~~~正確的答案是如下~~~

我相信我發現這裏的答案: http://www.deroneriksson.com/tutorials/java/spring/introduction-to-the-spring-framework/component-scanning-and-repository

的@Repository註解可以有一個特殊的角色,當談到例外轉換爲基於Spring的unchecked異常。回想一下,JdbcTemplate爲我們處理了這個任務。當我們使用Hibernate時,我們不打算使用Spring模板來處理基於Hibernate的異常到基於Spring的異常的轉換。因此,爲了自動處理這種轉換,使用@Repository註釋的Hibernate DAO將使用PersistenceExceptionTranslationPostProcessor將其Hibernate異常重新拋出爲Spring異常。

延伸閱讀:http://www.deroneriksson.com/tutorials/java/spring/introduction-to-the-spring-framework/hibernate-daos

上面明確的段落說: 回想一下JdbcTemplate的處理這個任務對於我們

因此,要回答我的問題,沒有必要使用jdbcTemplate使用PersistenceExceptionTranslationPostProcessor

1

是的,你可以,彈簧例外轉換機制可以透明地應用於與@Repository註釋的所有豆子 - 由上下文定義異常轉換bean後置處理器豆:

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

按照它doc

Bean後處理器,自動將持久性異常轉換應用於標有Spring的@Repository 註釋的任何bean,並添加相應的 P ersistenceExceptionTranslationAdvisor到公開的代理( 現有的AOP代理或實現目標接口的全部 的新生成的代理)。

平移原生資源的異常到Spring的DataAccessException層次結構。自動檢測實現PersistenceExceptionTranslator接口的bean,隨後請求 轉換候選異常。 所有的Spring的應用資源工廠(例如LocalContainerEntityManagerFactoryBean)實現 PersistenceExceptionTranslator這個接口開箱。作爲 的後果,啓用自動異常 翻譯通常需要的所有操作都是使用@Repository註釋標記所有受影響的Bean(例如存儲庫或 DAO),並將該後處理器定義爲應用程序上下文中的bean 。

所以,你可以用的JdbcTemplate以及與任何JPA供應商實現用它

按是DOC All of Spring's applicable resource factories (e.g. LocalContainerEntityManagerFactoryBean) implement the PersistenceExceptionTranslator interface out of the box,我覺得你還是需要使用PersistenceExceptionTranslationPostProcessor,因爲它使用的翻譯過程中產生的所有錯誤持久化過程(HibernateExceptions,PersistenceExceptions ...)放入DataAccessException對象中。

相關問題