小编典典

不允许在共享的EntityManager上创建事务-使用Spring事务或EJB CMT

hibernate

这篇文章是JPA的延续。如何在持久化后从数据库获取值

当我执行以下命令时,我将遵循以下异常,该如何解决呢?

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>

阅读 575

收藏
2020-06-20

共1个答案

小编典典

我猜这里的问题是,尽管您已经为事务管理器定义了bean,但是您没有注释@Transactional启用弹簧事务的create()方法。

还要删除该entityManager.getTransaction().commit();语句,因为现在所有事务管理都将在spring之前完成,如果您保留该语句不变,则将再次遇到相同的错误。

2020-06-20