As the title suggests, I'm using Apache Struts2 with JPA Eclipselink on my web application. Let's say that I have a couple of edit options there, in which most of them span only a single action and a single JSP page. In that cases that the approach I'm doing is the obvious one:
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager em = emfactory.createEntityManager();
em.getTransaction().begin();
Entity entity = em.find( Entity.class, this.id );
entity.setName("Test");
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
However, there is a more complex edit option that spans accross 4 different JSP pages (and even more actions). The approach I'm using is to store both the EntityManager and EntityTransaction objects in the session object (on the first edit action), and then retrieve it back in the last one, to finish the transactions. Something like this:
1. First edit action:
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
em = emfactory.createEntityManager();
et = em.getTransaction();
et.begin();
this.session.put("em", em);
this.session.put("et", et);
2. Last edit action:
em = (EntityManager) session.get("em");
et = (EntityTransaction) session.get("et");
entity.setName("Test");
et.commit();
em.close();
So, my question is: is this approach recommended? It seems to be working ok, but maybe there is a better, more reliable solution out there that I'm not aware of. What are your thoughts on this?