简体   繁体   中英

EJB Transactions

I am developing a Web Service using a Stateless EJB, which has a single entry point (method). This method has 3 steps and I want step 1 to occur in a different transaction than steps 2 and 3 (which should be in the same transaction). These "steps" consist in callings to injected Stateless EJBs. Let me explain with some code:

@Stateless  
@WebService(...)  
public class MyWebServiceImpl implements MyWebService { 

     @EJB  
     private UserBusinessBean userBusinessBean;  

     @EJB  
     private EventsBusinessBean eventsBusinessBean;  

     @WebMethod(...)  
     public MyWebServiceResult process(MyWebServiceParam param) {  
          // extract data from param  
          EventResult createEventResult = eventsBusinessBean.createEvent(data); // step 1  
          // do some extra processing  
          User user = userBusinessBean.createUser(someData); // step 2  
          // do some extra processing  
          EventResult updateEventResult = eventsBusinessBean.updateEvent(moreData); // step 3  
     }  
}  

The 2 injected EJBs are themselves Stateless and have injected references to Stateless DAOs, whose function is to call stored procedures on the database.

I need to have step 1 executing in one transaction and steps 2 and 3 executing in another transaction (because if step 2 or 3 fails, the info from step 1 is already committed).

I know I have 2 options to implement this: container-manager transactions or user-managed transactions. I believe the former approach is more safe than the latter, delegating the management to the container (in my case, a Weblogic server). But I can't understand how I should use the EJB Transactions Annotations to implement this logic. Should I annotate the methods from my injected Business Beans? And what about the DAOs, do they need to have annotations too? And which ones should I use?

I hope you can give me some help in this one. Let me know if you need to know more details from my implementation.

Because MyWebServiceImpl is an @Stateless , it will implicitly have a REQUIRED transaction attribute. To ensure step 1 is completed in its own transaction, you should add @TransactionAttribute(REQUIRES_NEW) to the EventsBusinessBean.createBean method. That will cause the bean to be created in its own transaction, and then the remaining actions in process will operate within another transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM