且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EJB事务在本地方法调用

更新时间:2023-12-04 21:15:40

你的调用 methodB()是方法的普通调用,不被EJB容器拦截;在运行时,EJB容器将注入代理,而不是您的类的实例,这是在调用方法之前拦截调用方式并设置环境。如果您使用这个,您直接调用方法,而不是通过代理。因此,两种方法都将使用相同的事务,无论ejb-jar.xml中通过EJB接口进行的调用定义什么。


In the following setup, does method B run in a (new) transaction?

An EJB, having two methods, method A and method B

public class MyEJB implements SessionBean
    public void methodA() {
       doImportantStuff();
       methodB();
       doMoreImportantStuff();
    }

    public void methodB() {
       doDatabaseThing();
    }
}

The EJB is container managed, with methodB in requires_new transaction, and method A in required transaction. thus:

<container-transaction id="MethodTransaction_1178709616940">
  <method id="MethodElement_1178709616955">
    <ejb-name>MyName</ejb-name>
    <method-name>*</method-name>
  <trans-attribute>Required</trans-attribute>
  </method>
  <method id="MethodElement_1178709616971">
    <ejb-name>MyName</ejb-name>
    <method-name>methodB</method-name>
  </method>
  <trans-attribute>RequiresNew</trans-attribute>
</container-transaction>

Now let another EJB call methodA with an EJB method call. methodA now runs in an transaction. Will the subsequent call to methodB from methodA run in the same transaction, or does it run in a new transaction? (mind, it's the actual code here. There is no explicit ejb-call to method B)

Your call to methodB() is an ordinary call of a method, not intercepted by the EJB container; at run-time the EJB container will inject a proxy and not an instance of your class, this is the way it intercepts calls and setup the environment before calling your method. If you use this you're calling a method directly and not through the proxy. Hence both methods will use the same transaction, regardless to what is defined in ejb-jar.xml for calls through EJB interfaces.