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的引用,就可以用這個引用治理自己的事務(wù)。 有狀態(tài)的會話bean的方法可以創(chuàng)建一個事務(wù),而且不用終止事務(wù)就可以返回。假如還有線程調(diào)用bean的方法,容器檢測是否有bean創(chuàng)建的活動的事務(wù),假如被調(diào)用的事務(wù)是同一個事務(wù),容器會答應(yīng)該線程重新進(jìn)入這個bean.假如bean在事務(wù)中且執(zhí)行不同事務(wù)上下文的線程試圖進(jìn)入bean,容器會阻塞這個線程直到bean的事務(wù)終止。假如線程試圖進(jìn)入事務(wù)時bean不在事務(wù)中,線程會執(zhí)行一個自己的事務(wù),容器會掛起線程當(dāng)前的事務(wù)以答應(yīng)線程進(jìn)入。一旦線程離開方法就會恢復(fù)線程以前的事務(wù),容器不會終止任何方法創(chuàng)建的事務(wù)。 對于無狀態(tài)會話bean和實體bean,當(dāng)事務(wù)活動時bean的方法不答應(yīng)返回。容器會為此拋出一個例外。 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.
會話同步接口 有狀態(tài)和無狀態(tài)的會話bean都可以訪問數(shù)據(jù)庫,并且參與一個事務(wù)。為了讓bean在事務(wù)中執(zhí)行它的任務(wù),bean開發(fā)者可以實現(xiàn)在bean中實現(xiàn)javax.ejb.SessionSynchronization接口。容器能自動檢測這個接口,容器會使用這個接口中的方法以使bean得到事務(wù)的狀態(tài)信息。實體bean不支持這個接口。因為實體bean are implicitly transaction aware,所以容器使用不同的方法控制一個事務(wù)中的實體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();