如何使用entityManager在JPA中启动事务

时间:2017-03-20 09:45:26

标签: java spring hibernate jpa transactions

我已经开始研究使用spring,hibernate,JPA,SOAP webservices的应用程序。现在要求必须在事务中运行某些查询。如果任何一个失败,整个事务应该回滚。

dao层中的代码如下:

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.hibernate.Session;

    public class BillDAOImpl implements BillDao{

             @PersistenceContext(type = PersistenceContextType.EXTENDED)
             private EntityManager em;

             public boolean processBills() throws Exception{

             EntityTransaction tx = null;
             Session session = null;

             try{

                 session = em.unwrap(Session.class);
                 tx = em.getTransaction();

                 Bill bill = em.find(Bill.class, billId);

                 //session.beginTransaction();
                 tx.begin();
                 ...
                 ...
                 em.persist(bill);
                 ...
                 ...
                 em.merge(<other object>);
                 ...
                 ...
                 //session.getTransaction().commit();
                 tx.commit();
             } catch(){
             }

             }

    }

执行tx = em.getTransaction()时,会出现以下错误:

java.lang.IllegalStateException: Cannot execute getTransaction() on a container-managed EntityManager

其他与交易相关的属性如下:

<bean id="tuneEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:persistenceXmlLocation="classpath*:META-INF/tune-persistence.xml"
        p:persistenceUnitName="tunePersistenceUnit" p:loadTimeWeaver-ref="loadTimeWeaver"
        p:jpaVendorAdapter-ref="jpaVendorAdapter" p:jpaDialect-ref="jpaDialect"
        p:dataSource-ref="tuneDbDataSource">
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.BTMTransactionManagerLookup
                </prop>
                <prop key="net.sf.ehcache.configurationResourceName">/${tune-db.ehcache.config.file}</prop>
                <prop key="hibernate.transaction.flush_before_completion">false</prop>              
                <prop key="hibernate.default_schema">${tune-db.schema}</prop>
                <prop key="org.hibernate.envers.default_schema">${tune-db.schema}</prop>
                <prop key="javax.persistence.validation.mode">${tune-db.data.validation}</prop>
                <prop key="hibernate.connection.isolation">3</prop>
                <prop key="hibernate.connection.release_mode">auto</prop>
                <prop key="hibernate.show_sql">${tune-db.hibernate.show-sql}</prop>
                <prop key="hibernate.format_sql">${tune-db.hibernate.format-sql}</prop>
            </props>
        </property>     
    </bean>

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

当我使用session.beginTransaction()session.getTransaction().commit()时,它可以正常工作。

但是我想用来自entityManager的交易替换它。那该怎么办?

4 个答案:

答案 0 :(得分:3)

尝试注入EntityManagerFactory,然后手动创建EntityManager:

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

public boolean processBills() throws Exception{

   EntityManager em = entityManagerFactory.createEntityManager();

   EntityTransaction tx = null;

   Session session = null;

   try{

       session = em.unwrap(Session.class);
       tx = em.getTransaction();

答案 1 :(得分:1)

@PersistenceContext返回的EntityManager实例始终是容器管理的EntityManager。容器管理的EntityManager始终是JTA EntityManagers,因此它们的生命周期由容器管理。我想现在有理由说为什么在它们上调用getTransaction()是违法的。This might help

答案 2 :(得分:0)

使用值hibernate.jta.allowTransactionAccess添加true属性,您应该可以手动使用它。虽然混合你的策略不是一个好习惯,但是有些代码是由JTA管理的,有些是手动的。

答案 3 :(得分:-1)

@Transactional注释将完全满足您的需求。

jsFiddle