EJB3 Transaction Propagation

后端 未结 8 1698
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 04:25

I have a stateless bean something like:

@Stateless
public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote {
    @PersistenceContext(unit         


        
8条回答
  •  时光取名叫无心
    2020-12-13 05:20

    Matt, the question you ask is a pretty classic one, I think the self-reference solution by Herval/Pascal is neat. There is a more general solution not mentioned here.

    This is a case for EJB "user" transactions. Since you are in a session bean you can get the user transaction from the session context. Here's how your code will look with user transactions:

    // supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1
    @Stateless
    @TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {
    
        @Resource
        private SessionContext ctx;
    
        @EJB
        private MyStatelessLocal1 myBean2;
    
        public void processObjects(List objs) {
            // this method just processes the data; no need for a transaction
            for(Object obj : objs) {
                this.myBean2.process(obj);
            }
        }
    
    
        public void process(Object obj) {
    
            UserTransaction tx = ctx.getUserTransaction();
    
            tx.begin();
    
            // do some work with obj that must be in the scope of a transaction
    
            this.mgr.merge(obj);
            // ...
            this.mgr.merge(obj);
            // ...
            this.mgr.flush();
    
            tx.commit();
        }
    }
    
        

    提交回复
    热议问题