tags:

views:

140

answers:

1

I'm currently using Java EE to inject my EntityManager into a web app as follows:

@PersistenceContext
EntityManager em;

@Resource
UserTransaction utx;

I have this in a request scoped JSF bean. It works, but it's a pain because to avoid the NoTransactionException I have to wrap every DAO method like so:

public void saveSomething(Obj toSave) {
 EntityManager em = getEntityManager();
 UserTransaction utx = getTransaction();

 try {

  utx.begin();

  em.persist(toSave);
  utx.commit();

 } catch(Exception e) {
  logger.error("Error saving",e);
  try {
   utx.rollback();
  } catch(Exception ne) {
   logger.error("Error saving",ne);
  }
  return null;
 }
}

}

Is there any way to have the container manage the transactions for me in a project like this consisting only of a WAR file?

+2  A: 

If you are managing your own transactions, the best way is to provide an abstract DAO to do the boilerplate code for you:

@PersistenceContext
EntityManager em;

@Resource
UserTransaction utx;

abstract class AbstractDao<E,ID> implements IDAO<E,ID> {

   public ID save(E e) {
        try {
                utx.begin();
                em.persist(e);
                utx.commit();

        } catch(Exception e) {
                logger.error("Error saving",e);
                try {
                        utx.rollback();
                } catch(Exception ne) {
                        logger.error("Error saving",ne);
                }
                return null;
        }
   }

}

The alternative is to use container-managed transactions. Please consult the J2EE guide: http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html

Miguel Ping