在jax-rs子资源中获取entitymanager?

时间:2016-08-03 22:37:08

标签: jax-rs jpa-2.0 websphere-8

在jax-rs子资源中获取entitymanager的正确方法是什么?

当我转到http://localhost/api/roots/1/branches时,记录器为em输出null。还尝试将em传递给构造函数并且“工作”因为它不是null,但是当我尝试持久化新分支时,它会抛出一个javax.persistence.TransactionRequiredException:PuId没有活动事务= TestAPIEAR#TestAPI.war #TestAPI < / p>

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;

    }
}

0 个答案:

没有答案