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

xdyibdwo  于 2023-05-16  发布在  Spring
关注(0)|答案(4)|浏览(224)

这篇文章是JPA How to get the value from database after persist的延续
当我执行下面的命令时,我得到了下面的异常,我该如何解决这个问题?

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>
u3r8eeie

u3r8eeie1#

我猜这里的问题是,尽管您已经为事务管理器定义了bean,但您还没有使用启用spring事务的@Transactional注解create()方法。
同时删除entityManager.getTransaction().commit();语句,因为现在所有的事务管理都将由spring处理,如果您保留该语句,那么您将再次获得相同的错误。

pbpqsu0x

pbpqsu0x2#

注入EntityManagerFactory而不是EntityManager和javax.transaction.Transactional方法注解解决了我的问题,如下所示。

//Autowire EntityManagerFactory
@PersistenceUnit(unitName = "readwrite.config")
private EntityManagerFactory entityManagerFactory;

//Use below code on create/update
EntityManager entityManager = entityManagerFactory.createEntityManager();

entityManager.getTransaction().begin();
if (!ObjectUtils.isEmpty(entity) && !entityManager.contains(entity)) {
   entityManager.persist(entity);
   entityManager.flush();
}
entityManager.getTransaction().commit();
zqdjd7g9

zqdjd7g93#

是否需要删除entityManager.getTransaction().begin() and annotate the method using@Transactional语句?这使Spring能够处理事务。

uz75evzq

uz75evzq4#

在我的例子里面Sping-boot这个解决方案工作

@Transactional(propagation = Propagation.NEVER)
public void myMethod() {

    SessionImplementor sessionImp = (SessionImplementor) em.getDelegate();
    var transaction = sessionImp.getTransaction();
    for (MyClass cls : lst) {
        try {
            transaction.begin();
            //do my stuffs with em
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
        }
    }
}

相关问题