views:

112

answers:

1

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]

Here's the spring entity manager factory configuration:

<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}" />

+2  A: 

It has nothing to do with the EntityManager. It is a transaction configuration problem. Apparently org.hibernate.transaction.JTATransactionFactory forces a JNDI lookup.

Switched to com.atomikos.icatch.jta.hibernate3.AtomikosJTATransactionFactory and everything works.

HDave