简体   繁体   中英

Null EntityManager Spring 4

I'm trying to setup entity manager with Spring 4 and I always get NullPointerException when I try to inject EntityManager with @PersistenceContext annotation.

I have Maven web application. Here's my applicationContext.xml configuration

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="EcommercePU">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.mysite.ecommerceapp.domain</value>
            <value>com.mysite.ecommerceapp.domain.*</value>
            <value>com.mysite.ecommerceapp.domain.*.*</value>
            <value>com.mysite.ecommerceapp.domain.*.*.*</value>
        </list>
    </property> 
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true"/>
        </bean>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
        </props>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/ecommercedb" />
    <property name="username" value="postgres" />
    <property name="password" value="test" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="persistenceExceptionTranslationPostProcessor"
     class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

applicationContext.xml is located under WEB-INF folder. Because I use NetBeans 8 I added Spring Framework support to my project from project properties -> Frameworks. I'm using EntityManager injection with file called GenericDaoImpl and here's it's code:

public abstract class GenericDaoImpl<E extends EntityClass> implements GenericDao<E> {

private Class<E> entityClass;

@PersistenceContext()
private EntityManager entityManager;

//Constructor
public GenericDaoImpl(final Class<E> entityClass) {
    this.entityClass = entityClass;
}

//Getters and Setters
public Class<E> getEntityClass() {
    return entityClass;
}

public void setEntityClass(final Class<E> entityClass) {
    this.entityClass = entityClass;
}

public EntityManager getEntityManager() {
    return entityManager;
}

public void setEntityManager(final EntityManager entityManager) {
    this.entityManager = entityManager;
}

public void checkEntityManager() {
    System.out.println("em: " + this.entityManager);
}
}

I have one test file where I simply print entity manager with checkEntityManager() method. Whenever I run it I always get null value for EntityManager. What could be wrong? My biggest doubt is that my applicationContext.xml is in wrong place or it is not used anywhere and thus it can't find configuration properties in applicationContext. I have tested moving applicationContext.xml file to resources folder but it didn't helped either. Other questions that I also have are following:

  1. Do I need to have persistence.xml? Since I use Spring 4 with packagesToScan feature I heard that persistence.xml is not required but I'm not sure.

  2. Is it wise to use hibernate to take care only basic entities cruds and other dao queries with JdbcTemplate?

All help would be appreciated.

I finally solved the problem and there were lots of things that has to be done.

  1. When I tested my Entity Manager through JUnit tests I got NullPointerException and reason was the configuration file was incorrect folder.

  2. applicationContext.xml was properly setup except there was a small problem that messed the whole file and that was <property name="persistenceUnitName" value="EcommercePU"> . Because I didn't had such persistence unit file in whole project it couldn't find it. When you add that property it doesn't mean that you have created a spring configuration file that has such persistence unit name. It simply means that if you want to provide persistence configurations to your LocalContainerEntityManagerFactory you would refer with that name to your persistence unit. This is not required in Spring 4.

  3. applicationContext.xml had to be moved from WEB-INF to resources folder.

  4. When you would run JUnit tests you should use @Autowired annotation to annotate DAO's.

  5. Dao implementation classes should have @Repository annotation.

  6. @Transactional annotation is required at least for CRUD methods if you are going to use. You can also annotate whole class. If you don't add @Transactional annotation EntityManager wouldn't execute persist, remove, update, find and other methods properly. Remember this is required if you are using Spring configurations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM