eastwater
eastwater

Reputation: 5620

JPA EntityManager.flush() is not called by java/jakarta EE container

JPA EntityManager.flush() is not called by glassfish 5.1 EE container.

In Java SE environment:

EntityTransaction t = em.getTransaction();
t.begin();

// persist entities
em.persist(entity);

t.commit();

commit() will flush entities in persistence context.

Java EE environment e.g. Glassfish:

@Stateless
public class DataManagerBean {
    @PersistenceContext
    EntityManager em;

    public void persist(Object entity) {
        em.persist(entity);
    }
}

JSF Bean:

@Named
@ViewScoped
public class FooBean  {
    @EJB
    DataManagerBean dataManagerBean;
    
    public void createFoo() {
        dataManagerBean.persist(foo);       
    }
} 

Application can not call em.getTransaction(). Transaction is managed by container. JPA provider entityManager.flush() is not called before entityManager.close() is called. As a result the entity is not created in database.

In EE environment, the database connection obtained by JPA provider EntityManager is the same as one used by container?

How does EE container tell JPA provider to flush entities to persistence if flush() is not called?

Upvotes: 1

Views: 269

Answers (1)

S. Kadakov
S. Kadakov

Reputation: 919

It is dependant on the way you calling your business method. In one word, beeing defaulted -- transaction begins when your flow enters FIRST business method (or Interceptor, decorating your first business method) and ends when your flow leaves last business method in the stack (or Interceptor, decorating your first business method).

You can manage transactions using @TransactionAttribute annotation with appropriate TransactionAttributeType (REQUIRED is default if not annotated). For example:

@Stateless
public class DataManagerBean {
    @PersistenceContext
    EntityManager em;

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void persist(Object entity) {
        em.persist(entity);
    }
}

In this case being called DataManagerBean.persist starts new transaction and commit and flush changes when being leaved. In case of error it will roll transaction back and throw exception you can catch at calling business method.

Upvotes: 0

Related Questions