JTA EntityManager无法使用getTransaction() [英] A JTA EntityManager cannot use getTransaction()

查看:1197
本文介绍了JTA EntityManager无法使用getTransaction()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在非ejb应用程序中使用以下代码。该代码有效。

How do I have the following code in my non-ejb application. The code works.

@Override
public void saveItems(Collection<T> items) {
    synchronized (em) {
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            for (T item : items) {
                saveItem_((Class<T>) null, item);
            }
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }
    }
}

In我正在使用EJB3 + JSF的新应用程序,并希望重用包含上述代码的库。我对新应用程序的持久性单元如下所示:

In a new application I'm using EJB3 + JSF and would like to re-use the library containing the code above. My peristence unit for the new application looks like this:

  <persistence-unit name="myApp" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>MySQLConnection</jta-data-source>
  </persistence-unit>

我的新应用程序在遇到此行时抛出异常:

My new application throw an exception when it hits this line:

    EntityTransaction tx = em.getTransaction();

例外情况是:

A JTA EntityManager cannot use getTransaction()

这很清楚。问题是如何转换我的代码以使容器管理的事务。大概我的bean方法需要适当注释......问题是如何?

Which is clear enough. The question is how would I convert my code to have the transactions managed by the container. Presumably my bean methods need to be annotated appropriately... The question is how?

推荐答案

EntityTransaction 与资源本地类型的实体管理器一起使用。如果你想使用JTA,那么必须使用 UserTransaction 界面。

EntityTransaction is used with entity manager of type resource local. If you want to use JTA, then have to use UserTransaction interface.

来自文档: EntityTransaction - 用于控制资源本地实体管理器上的事务的接口。 EntityManager.getTransaction()方法返回EntityTransaction接口。

From Documentation : EntityTransaction - Interface used to control transactions on resource-local entity managers. The EntityManager.getTransaction() method returns the EntityTransaction interface.

编辑:添加了伪代码。

@Resource
private SessionContext sessionContext;

void execute(){

UserTransaction userTxn = sessionContext.getUserTransaction();

try{

 userTxn.begin();
 /**
  *  do-something
  */
 userTxn.commit();

  } catch(Throwable e){
   userTxn.rollback(); //-- Include this in try-catch 
  }
}   

这篇关于JTA EntityManager无法使用getTransaction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆