Question

I am new both to EJB and Bean Managed Transactions. After scrapping the Internet, I found that I could write a EJ session Bean which does transactions the "bean-managed way", like this:

@TransactionManagement(value=TransactionManagementType.BEAN)
@Stateless
public class OperationBean {
    @Resource
    private UserTransaction userTransaction;
    public void operation() {
        try{
            userTransaction.begin();
            Op1();
            Op2();
            Op3();
            userTransaction.commit();
        } catch(Exception e){
            userTransaction.rollback();
        }
    }
}

However, I do not understand what happens if an exception is thrown by Op3(). How are Op1() and Op2() undone?

Another question is how do I bind this to JSF? I need to write a form in JSF that sends its data to the server and the OperationBean does 3 operations based on the received data. These operations do involve database operations(3 updates) and do not make sense individually.

Thanks!

Was it helpful?

Solution

When you call userTransaction.begin(), simply saying JTA begins transaction on database level. Now all the data modifications you perform are done inside transaction. If everything is OK, execution comes to userTransaction.commit() and database fixes transaction. If something's going wrong, you call userTransaction.rollback() in catch block and database drops all the modifications you do after begin().

In two words it is difficult to explain how database transactions work, but basically database isolates all changes during transaction from other clients until commit() or rollback() is called and prevents external updates of data you are working with.

In JSF you can create @ManagedBean and inject your OperationBean into it with @EJB annotation. You should get something like this

@ManagedBean
public class Operation {
    @EJB
    private OperationBean operationBean;

    public void doOperation() {
        operationBean.operation();
    }
}

and in your view

<h:form>
    <h:commandButton action="#{operation.doOperation}" value="Do Operation"/>
</h:form>

So you're doing it right. Assuming you really need bean managed transactions, not container managed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top