Using JSF, JPA and DAO. Without Spring?
Question
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.
Solution
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
OTHER TIPS
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.
Another option for you is to implement your DAO itself as a SLSB. That way you can inject the EntityManger rather than creating it. But it has it's own bad effects like too many session beans. chaining of the beans etc which is a sort of bad parctice.