Enterprise Java Development@TOPIC@

Chapter 105. Stateful Session Synchronization

105.1. Stateful Session Synchronization Events
105.2. Additional Stateful Rules
105.3. Summary

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);
    }