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.
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.
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
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.
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.