I have the following code:
JSF Managed Bean:
@ManagedBean(name = "purchaseView")
@ViewScoped
public class PurchaseView implements Serializable {
@EJB
private PurchaseService service;
private Order order;
// Getter/Setters here
public void checkoutOrder() {
// .. some checks for null here, then call service
service.checkout(order);
}
}
Service:
@Stateless
public class BuyVoucherService {
@EJB
private OrderBean orderBean;
@EJB
private ProductBean productBean;
public boolean checkout(Order order) {
orderBean.create(order);
for(int i=0;i<order.getQuantity();i++) {
Product product = new Product();
if(someCondition) {
// don't save anything and
return false;
}
// .. some setter here
product.setOrder(order);
productBean.create(product);
}
return true;
}
The productBean and orderBean are simple JPA EJB with the EntityManager and CRUD operation (Generated by Netbeans..).
In the Service above, things are persisted in the database when the Service returns. In the case something is wrong (someCondition == TRUE above), if I return false the orderBean.save(order) will still persist the order in the database, and I don’t want that.
Is throwing an EJBException and catching it in the ManagedBean the best option?
As you haven’t specified any transaction attribute explicitly, it will be most probably
Required, but depends on the server. Therefore both these methods will be within same transaction, so rolling back in a method will cascade the changes in another.You can also try using
Mandatoryattribute for the 2nd method, it will ensure that it requires a transaction to proceed further, else will cause runtime exception.Else, you can throw system exception, that will force the container to rollback the changes being made.