sourcecode

공유 EntityManager에서 트랜잭션을 생성할 수 없음 - Spring 트랜잭션 또는 EJB CMT 사용

codebag 2023. 8. 21. 21:15
반응형

공유 EntityManager에서 트랜잭션을 생성할 수 없음 - Spring 트랜잭션 또는 EJB CMT 사용

이 게시물은 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>

여기서 문제는 트랜잭션 관리자에 대한 빈을 정의했지만 create() 메서드에 주석을 달지 않았다는 것입니다.@Transactional스프링 트랜잭션을 활성화합니다.

또한 다음을 제거합니다.entityManager.getTransaction().commit();현재와 같은 명세서는 봄까지 모든 거래 관리가 처리될 것이고, 명세서를 그대로 두면 다시 같은 오류가 발생할 것입니다.

EntityManager 및 javax.transaction 대신 EntityManagerFactory를 주입합니다.메소드에 대한 트랜잭션 주석을 통해 아래와 같은 문제가 해결되었습니다.

//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();

문을 제거해야 합니다.entityManager.getTransaction().begin() and annotate the method using @거래?Spring에 의한 트랜잭션 처리를 가능하게 합니다.

내 경우 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();
        }
    }
}

언급URL : https://stackoverflow.com/questions/17860696/not-allowed-to-create-transaction-on-shared-entitymanager-use-spring-transacti

반응형