title: How to handle persistence context (EntityManager) with jax-rs sub-resource locators?
body: <p>I am using jax-rs restful web service in my application with sub-resource locators. However after passing entityManager to sub-resource I cannot persist any new objects in this sub-resource.</p>
  
  <p>The entityManager lets me however to query it for data.</p>
  
  <p>This is my main resource:</p>
  
  <pre><code>@Path("/registrations")
  @Stateless
  public class RegistrationsResource {
  
      @Context
      private UriInfo context;
  
      @PersistenceContext(unitName="pctx")
      private EntityManager em;
  
      public RegistrationsResource() {
      }
  
      //POST method ommited
  
      @Path("{regKey}")
      public RegistrationResource getRegistrationResource(@PathParam("regKey")
      String regKey) {
          return RegistrationResource.getInstance(regKey, em);
      }
  </code></pre>
  
  <p>}</p>
  
  <p>And this is my sub-resource:</p>
  
  <pre><code>public class RegistrationResource {
  
      private String regKey;
      private EntityManager em;
  
      private RegistrationResource(String regKey, EntityManager em) {
          this.regKey = regKey;
          this.em = em;
      }
  
      @Path("securityQuestion")
      @GET
      public String getQuestion() {
          return "iamahuman"+regKey;
      }
  
      @Path("securityQuestion")
      @POST
      public void postSecurityAnswer(String answer) {
          if(!answer.equals("iamahuman"+regKey)){
              throw new WebApplicationException(Status.BAD_REQUEST);
          }
  
          //Getting this information works properly
          List&lt;RegistrationEntity&gt; result = em.createNamedQuery("getRegistrationByKey")
              .setParameter("regKey", regKey).getResultList();
  
          switch(result.size()){
              case 0 :
                  throw new WebApplicationException(Status.NOT_FOUND);
              case 1:
                  break;
              default:
                  throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
              }
  
              RegistrationEntity reg = result.get(0);
              UserEntity newUser = new UserEntity();
  
              newUser.setHashedPassword(reg.getPwHash(), reg.getSalt());
              newUser.setUsername(reg.getUsername());
              newUser.setName(reg.getName());
              newUser.setSurname(reg.getSurname());
  
              //CRASHES HERE
              em.persist(newUser);
      }
  }
  </code></pre>
  
  <p>As you can see it takes registration object from database, creates new user for registration and tries to persist it. However, em.persist(newUser) throws TransactionRequiredException.</p>
  
  <p>My question is: how should I pass EntityManager to sub-resource so it can properly persist new objects?</p>