2014-11-15 104 views
2

我試圖附加一個攔截器到我的Hibernate JPA EntityManagerFactory下面的sds的方向this post,但與java配置。Spring數據JPA LocalEntityManagerFactoryBean getNativeEntityManagerFactory返回null

這裏是我的配置的相關部分:

@Bean 
public JpaTransactionManager transactionManager() { 
    JpaTransactionManager txm = new JpaTransactionManager(); 
    txm.setEntityManagerFactory(entityManagerFactory().getObject()); 
    return txm; 
} 

@SuppressWarnings("unchecked") 
@Bean 
public SynchronizedEntityChangeInterceptor synchronizedEntityChangeInterceptor() { 
    SynchronizedEntityChangeInterceptor synchronizedEntityChangeInterceptor = new SynchronizedEntityChangeInterceptor(); 
    synchronizedEntityChangeInterceptor.registerEntityClasses(Device.class, Artist.class); 
    return synchronizedEntityChangeInterceptor; 
} 

@Bean 
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); 
    entityManagerFactory.setDataSource(dataSource()); 
    entityManagerFactory.setPersistenceUnitName("metamp-client"); 
    entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); 
    Properties jpaProperties = new Properties(); 
    jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); 
    jpaProperties.put("hibernate.show_sql", "true"); 
    jpaProperties.put("hibernate.format_sql", "true"); 
    jpaProperties.put("hibernate.hbm2ddl.auto", "update"); 
    jpaProperties.put("hibernate.cache.use_second_level_cache", "false"); 
    entityManagerFactory.setJpaProperties(jpaProperties); 
    return entityManagerFactory; 
} 

@Bean 
public HibernateInterceptor hibernateInterceptor() { 
    HibernateInterceptor hibernateInterceptor = new HibernateInterceptor(); 
    if(entityManagerFactory().getNativeEntityManagerFactory() == null) 
      throw new NullPointerException("This shouldn't happen"); 
    hibernateInterceptor.setSessionFactory(
      ((HibernateEntityManagerFactory)entityManagerFactory() 
        .getNativeEntityManagerFactory()).unwrap(SessionFactory.class)); 
    hibernateInterceptor.setEntityInterceptor(synchronizedEntityChangeInterceptor()); 
    return hibernateInterceptor; 
} 

我的問題是,「這是不應該發生」總是會發生,所以getNativeEntityManagerFactory()返回null雖然春天文件說otherwise

這是一個錯誤,還是我做錯了什麼?

回答

1

您不應直接致電entityManagerFactory()。請嘗試以下操作:

@Bean 
public HibernateInterceptor hibernateInterceptor(
      LocalContainerEntityManagerFactoryBean factory) { 
    HibernateInterceptor hibernateInterceptor = new HibernateInterceptor(); 
    if(factory.getNativeEntityManagerFactory() == null) 
      throw new NullPointerException("This shouldn't happen"); 
    // rest of your code and use factory variable rather than entityManagerFactory()