如何从Spring上下文中配置的EntityManager获取连接?

时间:2014-09-05 08:24:51

标签: java spring jpa transactions dbunit

我希望从Spring上下文中配置的EntityManager获取连接,以便在dbunit DatabaseOperation.CLEAN_INSERT.execute方法中使用它。

这是Spring配置:

<bean id="testmEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <qualifier value="testm" type="org.springframework.beans.factory.annotation.Qualifier"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaDialect"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/></property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
        </props>
    </property>
   <property name="jpaVendorAdapter" ref="jpaAdapter"/>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
</bean>

 <bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
      p:driverClassName="org.h2.Driver"
      p:url="jdbc:h2:mem:test;IGNORECASE=TRUE;">
    <property name="autoCommit" value="false"/>
    <property name="suppressClose" value="true"/>
</bean>

<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>

 <tx:annotation-driven transaction-manager="testmTransactionManager"/>
<bean id="testmTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <qualifier value="testm"/>
    <property name="entityManagerFactory" ref="testmEntityManagerFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>

这是代码:

@javax.persistence.PersistenceContext(unitName = "testm")
@Qualifier(value = "testm")
protected javax.persistence.EntityManager emanager;


@Transactional
public void setUp() throws Exception {
    IDatabaseConnection connection = new DatabaseConnection (((SessionImpl)(emanager.getDelegate())).connection());

我收到例外org.hibernate.SessionException: Session is closed!

当我使用emanager.getTransaction ().begin ();时 我得到java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

解决: 使用数据源来获取它:

@Autowired
private DataSource dataSource;

dataSource.getConnection ()

1 个答案:

答案 0 :(得分:1)

在Spring中有两种使用事务的规范方法:

  1. 在方法上使用@Transactional注释

  2. 使用TransactionTemplate.execute方法

  3. 第二种方法使您可以使用单一方法执行多个事务。您不必手动启动和停止交易。

    数据库连接仅在spring事务处理单元内处于活动状态,因此在@Transactional方法内,在TransactionTemplate.execute()的回调方法中。