2012-02-03 63 views
2

我試圖注入eventRepository這是春數據倉庫在我的項目:定義HibernateExceptionTranslator:沒有在bean工廠找到持久性的異常轉化

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> 

但是,當我運行它我得到以下異常:

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

在一些評論中,我發現我需要「c圖HibernateExceptionTranslator「,但我沒有設法找出如何。

我正在嘗試關注official documentation,它沒有提及配置HibernateExceptionTranslator

感謝

回答

4

顯然溶液中加入

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

到beans.xml中

發現的解決方案感謝JB Nizet

1

在Java配置:

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

使用該進口如果使用休眠3:

import org.springframework.orm.hibernate3.HibernateExceptionTranslator; 

或這一個,如果使用休眠4:

import org.springframework.orm.hibernate4.HibernateExceptionTranslator; 
0

的根本原因是Java.lang.IllegalStateException這是不是hibernateException的子類如何彈簧的HibernateExceptionTranslator可以翻譯喲你的例外DataAccessException(Runtime Exception)

因此而不是HibernateExceptionTranslator在您的配置文件或applicationC0ntext-*.xml中添加org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor。然後在applicationC0ntext-*.xml或配置文件中用合適的組件掃描在持久性文件中標註@Repository註釋。

相關問題