users@glassfish.java.net

Stateful bean, extended persistence context and SessionSynchronization

From: Antonio Goncalves <antonio.mailing_at_gmail.com>
Date: Mon, 24 Sep 2007 11:37:57 +0200

Hi,

I'm using an extended persistence context in a Stateful bean. What I'm doing
is using the extended features to delay the commit/rollback of the
transaction to the end of my use case. Let's say I have a shopping cart with
a method that adds one item. This method would normally persists an Item in
the DB (em.persist) but because I use TransactionAttributeType.NOT_SUPPORTED,
it won't and the DB inserts will hold on. Once all the items are added to my
cart, I just use a checkout() method with
TransactionAttributeType.REQUIREDand flush the EntityManager. This
behaviour is woking fine and all my items
get persisted in one go. Here is the simplified code :


@Stateful
public class ShoppingCartBean implements ShoppingCartRemote,
SessionSynchronization {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;

    private List<Item> content = new ArrayList();

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void add(Item item) {
        content.add(item);
        em.persist(item);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Remove
    public void checkOut() {
        em.flush();
    }

    public void afterBegin() throws EJBException, RemoteException {
        System.out.println("=====> afterBegin");
    }

    public void beforeCompletion() throws EJBException, RemoteException {
        System.out.println("=====> beforeCompletion");
    }

    public void afterCompletion(boolean committed) throws EJBException,
RemoteException {
            System.out.println("=====> afterCompletion");
    }
}


As you can see on the code, I implement SessionSynchronization to see what's
happening before and after the transaction commits/rollbacks. I'm a bit
confused because this code will only produce one trace : "=====> afterBegin"
(and no beforeCompletion and afterCompletion which are not called). If I
change the add() method to REQUIRED then I'll get the 3 traces each time I
call the add() method, which is fine.

Do you know why I only get the afterBegin call and no
beforeCompletion/afterCompletion when I'm on NOT_SUPPORTED ?

Thanks,
Antonio