使用JSF,JPA和DAO.没有春天?

ich*_*rin 5 java jsf spring dao jpa

到目前为止,我仍然使用JSF和JPA而没有DAO.现在我想使用DAO.但是如何在DAO-Classes中初始化EntityManager?

public class AdresseHome {

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Adresse transientInstance) {
        log.debug("persisting Adresse instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有没有使用Spring,还是有没有Spring的解决方案?

谢谢.

Pas*_*ent 5

Java EE 5不支持非托管组件中的注入,因此如果没有Spring,您将不得不在此处使用应用程序管理的实体管理器(并因此在应用程序级别管理其生命周期).

实际上,Java EE 5+并不真正提倡使用DAO模式(JPA Killed DAO?是关于这个主题的一篇很好的文章)并包装实现Domain Store模式的实体管理器,它实际上完成了DAO的工作.在我看来,在DAO中没有任何意义.


nos*_*nos 5

如果您的容器没有为您注入EntityManager,您可以使用以下内容:

EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("jpatest");
EntityManager em = factory.createEntityManager();
Run Code Online (Sandbox Code Playgroud)

来自persistence.xml中定义的单元的"jpatest"