views:

487

answers:

2

Hi,

till now i still worked with JSF and JPA without DAOs. Now i'd like to use DAOs. But how can i initialize the EntityManager in the DAO-Classes?

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;
        }
    }
}

Have I to use Spring or is there a solution that works without Spring?

Thanks.

A: 

Java EE 5 doesn't support injection in non managed component so without Spring you'll have to use an application-managed entity manager here (and consequently to manage its lifecycle at the application level).

Actually, Java EE 5+ doesn't really advocates using the DAO pattern (Has JPA Killed the DAO? is a nice article on this topic) and wrapping the entity manager which implements the Domain Store pattern, which does pretty much of what DAO does, in a DAO doesn't really make sense in my opinion.

Pascal Thivent
+4  A: 

If your container doesn't inject the EntityManager for you, you can get one with:

EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("jpatest");
EntityManager em = factory.createEntityManager();

Where "jpatest" from the unit defined in your persistence.xml

nos
So I Still need to create an EntityManager for each DAO?
ich-bin-drin