java.lang.NullPointerException upon EntityManager injection in Spring repository

非 Y 不嫁゛ 提交于 2019-12-04 12:39:03

I know this question is over 9 month old, but I stumbled over the same problem and managed to fix it. The solution from Andrei Stefan is one step in the right direction. Surprisingly, when you call getObject() within the method to retrieve the entityManagerFactory, it will throw a NPE, but if you call the exact same method outside of the entityManagerFactory method it will work.

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory().getObject());
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");

        factory.setJpaVendorAdapter(jpaVendorAdapter);
        return factory;
    }

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }

The initialization logic of LocalContainerEntityManagerFactoryBean is in the afterPropertiesSet() method. Usually it is called by Spring after all properties have been set. You have to call afterPropertiesSet() before calling getObject() if you manually instantiate the bean. Otherwise you'll get a NullPointerException.

Try

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    ...
    return localContainerEntityManagerFactoryBean;
}

instead of

@Bean
public EntityManagerFactory entityManagerFactory() {
    ...
    return localContainerEntityManagerFactoryBean.getObject();
}

@charleyDc5 does your application context (spring-servlet.xml) includes < context:component-scan >. Is the @repository package included in it. some times this might be a cause for this issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!