Tom Tucker
Tom Tucker

Reputation: 11916

Translating PersistenceException to DataAccessException in Spring

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!

Upvotes: 7

Views: 4722

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 341003

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>

Upvotes: 9

Related Questions