1

What is the correct way to get entitymanager in a jax-rs subresource?

When I go to http://localhost/api/roots/1/branches the logger outputs null for the em. Also tried passing em into the constructor and that "works" as it is not null, but when I try to persist a new branch it throws a javax.persistence.TransactionRequiredException: No active transaction for PuId=TestAPIEAR#TestAPI.war#TestAPI

RootResource.java

@Path(value = "/roots")
@Stateless
public class RootResource {

    @Context
    UriInfo uriInfo;

    @PersistenceContext(unitName = "TestAPI")
    private EntityManager em;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Root> getRoots() {
        TypedQuery<Root> query = em
                .createNamedQuery("Root.findAll", Root.class);

        List<Root> rootList = query.getResultList();

        return rootList;

    }

    // Sub Resources
    @Path("{rootid}/branches")
    @Produces(MediaType.APPLICATION_JSON)
    public BranchResource getBranches() {
        return new BranchResource();
    }

}

BranchResource.java

@Path("/")
@Stateless
public class BranchResource {

    @PersistenceContext(unitName = "TestAPI")
    private EntityManager em;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Branch> getBranches(@Context UriInfo uriInfo,
            @PathParam("rootid") long rootId) {
        logger.info("Entity Manager: " + em);
        TypedQuery<BriefcaseContent> query = em.createNamedQuery(
                "Branch.findAllforRoot", Branch.class);
        query.setParameter("rootid", rootId);

        List<Branch> branchList = query.getResultList();

        return branchList;

    }
}
Carlos
  • 1,696
  • 1
  • 14
  • 21
  • 3
    The answer from mirko-klemm for question http://stackoverflow.com/questions/5734734/how-to-handle-persistence-context-entitymanager-with-jax-rs-sub-resource-locat resolved the issue. – Carlos Aug 04 '16 at 14:00

0 Answers0