Public interface javax.ejb.EJBContext { public Identity getCallerIdentity(); public boolean isCallerInRole(Identity other); public EJBHome getEJBHome(); public PRoperties getEnvironment(); public UserTransaction getUserTransaction() throwsIllegalStateException; public boolean getRollbackOnly(); public void set RollbackOnly(); }
一旦bean獲得了一個UserTransaction的引用,就可以用這個引用治理自己的事務。 有狀態的會話bean的方法可以創建一個事務,而且不用終止事務就可以返回。假如還有線程調用bean的方法,容器檢測是否有bean創建的活動的事務,假如被調用的事務是同一個事務,容器會答應該線程重新進入這個bean.假如bean在事務中且執行不同事務上下文的線程試圖進入bean,容器會阻塞這個線程直到bean的事務終止。假如線程試圖進入事務時bean不在事務中,線程會執行一個自己的事務,容器會掛起線程當前的事務以答應線程進入。一旦線程離開方法就會恢復線程以前的事務,容器不會終止任何方法創建的事務。 對于無狀態會話bean和實體bean,當事務活動時bean的方法不答應返回。容器會為此拋出一個例外。 Leaving a tranaction active across method calls is stateful,and is not allowed for stateless session beans.Fro similar reasons,entity beans are also not allowed to maintain an open transaction state across method calls when the bean has declared the TX_BEAN_MANAGED transaction control.
會話同步接口 有狀態和無狀態的會話bean都可以訪問數據庫,并且參與一個事務。為了讓bean在事務中執行它的任務,bean開發者可以實現在bean中實現javax.ejb.SessionSynchronization接口。容器能自動檢測這個接口,容器會使用這個接口中的方法以使bean得到事務的狀態信息。實體bean不支持這個接口。因為實體bean are implicitly transaction aware,所以容器使用不同的方法控制一個事務中的實體bean.
SessionSynchronization接口定義如下: public interface javax.ejb.SessionSynchronization { public void afterBegin() throws RemoteException; public void beforeCompletion() throws RemoteException; public void afterCompletion(boolean yn) throws RemoteException; }
Current current = new Current(); Current.setServiceProvider(txMgrURL); Current.create(); Current.begin(); Current.doSomeWork(); RemRef1.doSomeWork(); RemRef2.doMoreWork(); Current.commit();