在Spring中将PersistenceException转换为DataAccessException

Tom*_*ker 6 java spring jpa

我正试图在Spring + JPA + Hibernate环境中处理唯一的键约束违规.

PersistenceExceptionTranslationPostProcessor用来翻译PersistenceException一个DataAccessException.当有一个唯一的键约束违规时,我会期待一个DuplicateKeyException或一个DataIntegrityViolationException抛出,但我得到的是一个JpaSystemException包装PersistenceException.

使用DataAccessException层次结构的重点不在于它的细粒度足以不必查找特定于供应商的错误代码吗?

我如何将Spring翻译PersistenceException成更具体的DataAccessException

编辑:我注意到DataAccessUtils.translateIfNecessary()中的this.jpaDialect为null.我需要配置一些设置来将this.jpaDialect设置为HibernateJpaDialect吗?

谢谢!

Tom*_*icz 9

显然你没有jpaDialect设定.对于Hibernate,它应该如下所示:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <!-- ... -->
</bean>
Run Code Online (Sandbox Code Playgroud)