I have a simple EJB stateless class with two methods, both without @TransactionAttribute. The first method saves beer and invokes another one which saves other beer and throws an exception.
@Stateless
public class EJBContainer {
@PersistenceContext
EntityManager em;
public void testTransaction() {
em.persist(getBeer("Corona"));
try {
saveAndThrowException();
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveAndThrowException() {
em.persist(getBeer("Heineken"));
throw new RuntimeException();
}
//getBeer() definition
}
I assumed that both methods would use default transaction type (required) - so a new transaction will be created in the first method and it will be used in the second method. So throwing an exception should rollback this transaction and no beers will be saved by EntityManager. But it turned out that both beers have been saved. Where am I wrong?
When I moved a second method to the other stateless EJB it worked as I had supposed - the first EJB created new transaction, the second used it, exception caused a rollback and no beers had been saved.
The EJB is called from this JAX-RS client:
@ApplicationScoped
public class BeerController {
@Inject
private EJBContainer ejbContainer;
@POST
public void addBeer() {
ejbContainer.testTransaction();
}
}
@ApplicationScoped public class BeerController { @Inject private EJBContainer ejbContainer; @POST public void addBeer() { ejbContainer.testTransaction(); } }
– Aleksander Ka