2013-07-25 37 views
18

這篇文章是在JPA How to get the value from database after persist不允許在共享的EntityManager創建事務 - 使用Spring的事務或EJB CMT

繼續當我執行下面我得到以下異常,我怎麼能解決這個問題?

Not allowed to create transaction on shared EntityManager - use Spring 
transactions or EJB CMT 

DAOImpl代碼

public void create(Project project) { 
     entityManager.persist(project); 
     entityManager.getTransaction().commit(); 
     project = entityManager.find(Project.class, project.getProjectId()); 
     entityManager.refresh(project); 
     System.out.println("Id -- " + project.getProjectId()); 
      System.out.println("no -- " + project.getProjectNo()); 
    } 

的applicationContext.xml

<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:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <bean id="DataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="username" value="scott" /> 
     <property name="password" value="tiger" /> 
     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> 
     <property name="url" value="jdbc:oracle:thin:@myserver:1521:ORCL" /> 
    </bean> 

    <bean id="entityManagerFactory" 
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="dataSource" ref="DataSource" /> 
     <property name="packagesToScan" value="test.entity" /> 
     <property name="jpaVendorAdapter"> 
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
       <property name="showSql" value="true" /> 
       <property name="generateDdl" value="false" /> 
       <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" /> 
      </bean> 
     </property> 
    </bean> 

    <context:component-scan base-package="test.net" /> 

    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="entityManagerFactory" /> 
    </bean>   

    <context:annotation-config/> 

</beans> 

回答

25

我想這裏的問題是,雖然您已經定義了豆的事務管理器,你的避風港沒有註釋create()方法@Transactional,它啓用了spring事務秒。

也刪除entityManager.getTransaction().commit();語句,因爲現在所有的事務管理都將在spring中處理,如果將語句保留原樣,那麼您將再次得到相同的錯誤。

相關問題