简体   繁体   中英

How to manage java ee transactions?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM