Defining HibernateExceptionTranslator: No persistence exception translators found in bean factory

10,093

Solution 1

Obviously the solution was adding

     <bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

to beans.xml

Solution found thanks to JB Nizet.

Solution 2

With Java Config:

@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
    return new HibernateExceptionTranslator();
}

Using this import if using Hibernate 3:

import org.springframework.orm.hibernate3.HibernateExceptionTranslator;

or this one if using Hibernate 4:

import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
Share:
10,093
Vojtěch
Author by

Vojtěch

Updated on September 05, 2022

Comments

  • Vojtěch
    Vojtěch over 1 year

    I am trying to inject a eventRepository which is Spring Data Repository in my project:

    public class App {
    
        protected static EntityManagerFactory factory;
    
        @Autowired
        protected EventRepository eventRepository;
    
        public void execute() {
            Event foo = eventRepository.findBySlug("abraxas");
        }
    
        public static void main(String[] args) {
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("beans.xml");
    
            App runner = (App) context.getBean("AppBean");
            runner.execute();
        }
    }
    

    beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:jpa="http://www.springframework.org/schema/data/jpa"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/data/jpa
                http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
        <bean id="AppBean" class="org.app.App"></bean>
        <jpa:repositories base-package="org.app.repository" />
    </beans>
    

    But when I run it I get following exception:

    java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators
    

    In some comments I found I need to "configure HibernateExceptionTranslator", but I did not manage to find out how.

    I am trying to follow the official documentation which does not mention configuration of HibernateExceptionTranslator.

    Thanks