jakarta-eejpaentitymanageropen-session-in-view

Open EntityManager in View in JPA for Java EE


I am searching for how to implement Open EntityManager In View pattern in JPA. However all I can find is for Hibernate (Open Session In View) or Spring.

Could any of you give an example (with code if possible) on how to implement Open EntityManager In View pattern for JPA and Java EE?


Solution

  • There is a nice explanation of such an implementation in the very recommendable Pro JPA 2 Book, chapter 6, topic 'Avoiding Detachment'.

    I will try to give some hints, but do read it up - the book presents several alternative approaches and discusses their respective pros and cons.

    With JPA, there are two ways to approach the issue. First is to work with detached entities in the view and an extended persistence context (PC) in the backend. The second is to keep a single transaction alive as long as the view is active. I suppose we are talking about the second strategy here - it is called 'Transaction View' in the book.

    An important point is that the second scenario does not work for remote clients. Once you have to serialize your entities, the serialized (and then the deserialized) representation is not in any way attached to a PC.

    Querying and rendering must happen during the same transaction in order to use a TX-scoped PC. You will need to use a UserTransaction instead of relying on CMT (you can still use CMT in the backend beans).

    The gist:

    public class MyServlet extends HttpServlet {
    
      @Resource UserTransaction tx;
      @EJB MyService bean;
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        // ...
        try {
          tx.begin();
    
          List entities = bean.findAll();
          request.setAttribute("entities", entities);
          getServletContext().getRequestDispatcher("/listEntities.jsp")
          .forward(request, response);
    
        } finally {
          tx.commit();
        }
      // ...
      }
    }
    

    The book illustrates the use of this pattern for a JPS page. I am not sure how you would map this approach to other frameworks like JSF or Wicket.