从JSP获取EntityManger和UserTransaction的最佳实践 [英] Best practice to get EntityManger and UserTransaction from JSP
问题描述
我目前正在尝试找出在我的应用程序中获取实体管理器和usertransaction的最佳方法。
I am currently trying to figure out the best way to get a entity manager and a usertransaction in my application.
在JBoss 5.1中,我能够直接注入它进入JSP文件,但不再允许这样做:
In JBoss 5.1 I was able to inject it directly into the JSP file, but this is not permitted anymore:
<%!@PersistenceContext(unitName = "unitname")
public EntityManager em;
@Resource
UserTransaction utx;
%>
我必须访问 em
和 utx
来自我的应用程序中的不同位置,例如Servlet和Controller类。因此,将它放在一个地方并在全球范围内访问它会很棒,但我还没弄清楚如何做到这一点。任何提示都将不胜感激。
I have to access em
and utx
from different locations in my application such as Servlets and Controller classes. So it would be great to have it in one place and to access it globally, but I did not figure out yet how to do it. Any hint would be appreciated.
推荐答案
我发现了如何在Servlet,Controller类和JSP文件中获取EntityManager和UserTransaction 。
I found out how to get the EntityManager and the UserTransaction in Servlets, Controller Classes and JSP files.
让我们从SessionBeans开始。我将所有控制器类重新定义为无状态SessionBeans。会话Bean允许资源注入。这就是我这样做的:
Let's start with SessionBeans. I redefined all my controller classes as Stateless SessionBeans. Session Beans allow ressource injection. This is how I did it:
@Stateless
public class UserHandling {
@PersistenceContext(unitName = "SSIS2")
private static EntityManager em;
@Resource
private UserTransaction utx;
public User getUser(int userId) {
User userObject = em.find(User.class, userId);
return userObject;
}
}
如果会话Bean类中需要另一个会话Bean ,它可以注入 @EJB
注释:
If another Session Bean is needed in a Session Bean Class, it can be injected with the @EJB
annotation:
@Stateless
public class UserHandling {
@PersistenceContext(unitName = "SSIS2")
private static EntityManager em;
@Resource
private UserTransaction utx;
@EJB
UserHandling uh; RoleHandling rh;
public User getUser(int userId) {
User userObject = em.find(User.class, userId);
return userObject;
}
}
在JSP文件中,您可以获得会话Bean控制器通过查找InitialContext的类:
In JSP files, you can get the Session Bean Controller classes by lookup the InitialContext:
<%
InitialContext ic = new InitialContext();
UserHandling uh = (UserHandling) ic.lookup("java:app/" + application.getContextPath() + "/UserHandling");
%>
这篇关于从JSP获取EntityManger和UserTransaction的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!