jpaejb-3.1

EJB Transaction between @LocalBean's methods


I have a @Stateless @LocalBean which looks like this

@LocalBean
@Stateless
class TokenBean {

    public Token signOn() {       <--------+
        /* Do some JPA things. */          |
    }                                      |
                                           |
    public Token logIn() {                 |
        /* Do some JPA things. */          |
        return signOn();           --------+
    }

    @PersistenceContext
    private EntityManager entityManager;
}

Within JTA, How can I commit the transaction in a method before calling other methods? Do I just have to call flush() on the entityManager? (Actually I'm doing this)

I tried @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) but I don't think it's not for this situation.


Solution

  • entityManager.flush() should be enough, and it will syncronize all attached (to the current persitence context ) entities to the database. The @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) will start a new transaction for you for every method you call but it won't commit your data unless you exit the method.