How to create JPA EntityMananger in Spring Context?
- by HDave
I have a JPA/Spring application that uses Hibernate as the JPA provider. In one portion of the code, I have to manually create a DAO in my application with the new operator rather than use Spring DI. When I do this, the @PersistenceContext annotation is not processed by Spring.
In my code where I create the DAO I have an EntityManagerFactory which I used to set the entityManager as follows:
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
MyDAO dao = new MyDAOImpl();
dao.setEntityManager(entityManagerFactory.createEntityManager());
The problem is that when I do this, I get a Hibernate error:
Could not find UserTransaction in JNDI [java:comp/UserTransaction]
It's as if the HibernateEntityManager never received all the settings I've configured in Spring:
<bean id="myAppTestLocalEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myapp-core" />
<property name="persistenceUnitPostProcessors">
<bean class="com.myapp.core.persist.util.JtaPersistenceUnitPostProcessor">
<property name="jtaDataSource" ref="myappPersistTestJdbcDataSource" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
<prop key="hibernate.transaction.manager_lookup_class">com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<!-- The following use the PropertyPlaceholderConfigurer but it doesn't work in Eclipse -->
<property name="database" value="$DS{hibernate.database}" />
<property name="databasePlatform" value="$DS{hibernate.dialect}" />
I am not sure, but I think the issue might be that I am not creating the entity manager correctly with the plain vanilla createEntityManager() call rather than passing in a map of properties. I say this because when Spring's LocalContainerEntityManagerFactoryBean proxy's the call to Hibernate's createEntityManager() all of the Spring configured options are missing. That is, there is no Map argument to the createEntityManager() call.
Perhaps it is another problem entirely however....not sure!