简体   繁体   English

如何管理Java EE交易?

[英]How to manage java ee transactions?

I'm currently using Java EE to inject my EntityManager into a web app as follows: 我目前正在使用Java EE将EntityManager注入Web应用程序,如下所示:

@PersistenceContext
EntityManager em;

@Resource
UserTransaction utx;

I have this in a request scoped JSF bean. 我在请求范围内的JSF Bean中拥有此功能。 It works, but it's a pain because to avoid the NoTransactionException I have to wrap every DAO method like so: 它可以工作,但是很痛苦,因为要避免NoTransactionException,我必须像这样包装每个DAO方法:

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? 有什么办法可以让容器在仅由WAR文件组成的项目中为我管理事务?

If you are managing your own transactions, the best way is to provide an abstract DAO to do the boilerplate code for you: 如果您要管理自己的交易,最好的方法是提供一个抽象的DAO为您完成样板代码:

@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 请查阅J2EE指南: http : //java.sun.com/javaee/5/docs/tutorial/doc/bncij.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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