Enterprise Java Development@TOPIC@
Stateful session EJBs using container-managed transactions can receive transaction events
EJBs using bean-managed transactions are in control of their transaction and do not need events
Figure 105.1. Example: Stateful EJB with Transaction Callbacks
@Stateful public class TxWatcherEJB { ... /** * By calling this (or any other business method, the sessionEJB will be created * and enlisted in the current transaction */ public void watchTransaction(Class<?> clazz, int hashCode) { String txName = clazz.getSimpleName() + ":" + hashCode; if (this.txName==null || !this.txName.equals(txName)) { logger = LoggerFactory.getLogger(clazz); logger.debug("watcher EJB {} enlisted in transaction for {}", beanName, txName); this.txName = txName; } else { logger.debug("transaction continued for {}", this.txName); } } @AfterBegin public void afterBegin() { logger.debug("transaction for {} has started", beanName); } @BeforeCompletion public void beforeCompletion() { logger.debug("transaction for {} is committing", beanName); } @AfterCompletion public void afterCompletion(boolean committed) { logger.debug("transaction committed for {}, commited={}", beanName, committed); }
Implement a javax.ejb.SessionSynchronization
callback interface or use annotations
Annotate methods -- no more than once per annotation
afterBegin()/@AfterBegin
Executed within the transaction, prior to first business method
beforeCompletion()/@BeforeCompletion
Executed after last business method complete -- chance to rollback
afterCompletions(boolean)/@AfterCompletion
Executed after transaction complete with a boolean complete
providing status
Cannot be final or static
A stateful session EJB may participate in only a single transaction at a time
A stateful session EJB will not be passivated while in an active transaction
A stateful session EJB's conversational state is not transactional
i.e., it is not automatically rolled back