Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to get EntityManger and UserTransaction from JSP

I am currently trying to figure out the best way to get a entity manager and a usertransaction in my application.

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

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.

like image 793
nimrod Avatar asked Feb 20 '23 16:02

nimrod


1 Answers

I found out how to get the EntityManager and the UserTransaction in Servlets, Controller Classes and JSP files.

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

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

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");
%>
like image 197
nimrod Avatar answered Mar 11 '23 18:03

nimrod