Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating PersistenceException to DataAccessException in Spring

Tags:

java

spring

jpa

I'm trying to handle unique key constraint violations in a Spring + JPA + Hibernate environment.

I use PersistenceExceptionTranslationPostProcessor to translate a PersistenceException to a DataAccessException. When there's a unique key constraint violation, I'd expect a DuplicateKeyException or a DataIntegrityViolationException thrown, but all I get is a JpaSystemException that wraps a PersistenceException.

Isn't the whole point of using the DataAccessException hierarchy that it's fine-grained enough not to have to look up the vendor-specific error code?

How do I have Spring translate a PersistenceException to a more specific DataAccessException ?

EDIT: I noticed that this.jpaDialect in DataAccessUtils.translateIfNecessary() is null. Is there some setting I need to configure to set this.jpaDialect to HibernateJpaDialect?

Thanks!

like image 720
Tom Tucker Avatar asked Feb 25 '11 18:02

Tom Tucker


1 Answers

Apparently you don't have jpaDialect set. For Hibernate it should look like this:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <!-- ... -->
</bean>
like image 149
Tomasz Nurkiewicz Avatar answered Sep 26 '22 07:09

Tomasz Nurkiewicz