我以前使用RESOURCE-LOCAL事务类型为Hibernate配置了这个配置:
的persistence.xml:
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</persistence-unit>
applicationContext(dataaccess bit):
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"></bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="persistenceUnitName" value="myPU"/>
<property name="jpaProperties">
<props>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- Are there any other properties required? -->
</bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/CNTXESDB" />
<property name="lookupOnStartup" value="true" />
<property name="cache" value="true" />
<property name="proxyInterface" value="javax.sql.DataSource" />
</bean>
但是这种交易似乎不适用于Glassfish,所以我不得不切换到JTA交易。
问题是 - 让Spring管理事务创建(通过@Transactional)我需要定义一个TransactionManager
bean但是spring-tx中包含的JtaTransactionManager
不接受entityManagerFactory bean,所以它不知道entityManager在哪里打开/关闭/刷新Hibernate会话。
那么如何使用Hibernate配置Spring来使用JTA事务呢?
修改
事实证明可以使用与Glassfish的RESOURCE_LOCAL事务,但不知何故,您不能拥有persistence.xml文件。我将此文件重命名为my_persistence.xml
并配置LocalContainerEntityManagerFactoryBean
,如下所示:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="persistenceUnitName" value="myPU"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/my_persistence.xml" />
<property name="jpaProperties">
<props>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
答案 0 :(得分:1)
我有类似的问题,最后我解决了你在这个小小的演示中看到的: https://github.com/miguelangelprogramacion/spring4_jpa_hibernate
以[1]作为参考,我更喜欢在JTA之前使用Spring的事务支持。
另外,我使用了基于注释的方法。
[1] http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/