使用 JSF、JPA 和 DAO。没有春天?
到目前为止,我仍然在没有 DAO 的情况下使用 JSF 和 JPA。现在我想使用 DAO。但是我如何在 DAO 类中初始化 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;
}
}
}
我必须使用 Spring 还是有一个无需 Spring 也能工作的解决方案?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的容器没有为您注入 EntityManager,您可以使用以下命令获取一个:
其中 “jpatest” 来自 persistence.xml 中定义的单元
If your container doesn't inject the EntityManager for you, you can get one with:
Where "jpatest" from the unit defined in your persistence.xml
Java EE 5 不支持非托管组件中的注入,因此如果没有 Spring,您必须在此处使用应用程序管理的实体管理器(从而在应用程序级别管理其生命周期)。
实际上,Java EE 5+ 并不真正提倡使用 DAO 模式(Has JPA Killed DAO? 是关于这个主题的一篇很好的文章)并包装了实现 的实体管理器域存储 模式几乎完成了 DAO 的大部分工作,但在我看来,在 DAO 中并没有真正的意义。
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.
您的另一个选择是将 DAO 本身实现为 SLSB。这样您就可以注入 EntityManger 而不是创建它。但它也有其自身的不良影响,例如会话 bean 过多。豆子等的链接是一种不好的做法。
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.