简体   繁体   中英

Hibernate & Spring: EntityManager is Null

I'm setting up a Project with Spring and Hibernate. I created an abstract DAO class that contains an EntityManager. When I want to use this EntityManager, it's null and I dont understand why. Maybe you can help me.

My persistence-context

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
   http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<import resource="persistence-beans.xml" />
<mvc:annotation-driven />

<bean id="jdbcPropertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="classpath:META-INF/mysql.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
    p:username="${jdbc.username}" p:password="${jdbc.password}" />

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="${hibernate.show_sql}" />
            <property name="generateDdl" value="${hibernate.generate_ddl}" />
            <property name="databasePlatform" value="${hibernate.dialect}" />
        </bean>
    </property>
</bean>

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

PersonDao.java:

@Repository
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class PersonDao extends AbstractDao<Person> {

    public PersonDao() {
    super(Person.class);
}
}

AbstractDao.java

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public abstract class AbstractDao<T> {

@PersistenceContext
protected EntityManager em;

private Class<T> entityClass;

public AbstractDao(Class<T> entityClass) {
    this.entityClass = entityClass;
}

public AbstractDao() {
}

public void create(T entity) {
    this.em.persist(entity);
}

public void edit(T entity) {
    this.em.merge(entity);
}

public void remove(T entity) {
    this.em.remove(this.em.merge(entity));
}

public T find(long primaryKey) {
    return this.em.find(entityClass, primaryKey);
}

@SuppressWarnings("rawtypes")
public List<T> findAll() {
    CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    return this.em.createQuery(cq).getResultList();
}

}

Thanks in advance!

An entity manager can only be injected in transaction classes. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

but your AbstractDAO is not EJB you can not use EntityManager directly.

solution

@PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;

EntityManager entityManager = entityManagerFactory.createEntityManager();

then perform operation using emtityManager.

alternatively you can use container managed Transaction using JNDI lookup..

let me know for any issues.

Try adding <context:annotation-config /> to your persistence-context. This section of the reference manual may help you to use @PersistenceContext .

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