I am new to Java EE so my question may be very basic. I have built following REST web service with Stateless session bean (simplyfied):
@Path("/list/")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Stateless
public class ListResource {
@PersistenceContext(unitName = "unitName")
private EntityManager em;
@GET
@Path("/")
public List<Compound> getCompounds() {
List<Compound> list = tq.getResultList();
if (list.isEmpty()) {
throw new WebApplicationException(Response.status(404).entity("There are no compounds in database.").build());
}
return list;
}
}
It works like charm. Its accessible via URL and return JSON. Problem is that I have another part of the program written in plain Java that needs to use this Session bean as some kind of model to get all Compounds.
Problem is that when I initialize this Session bean somewhere it is outside of persistence context and therefore doesnt know EntityManager to access database. I believe.
I dont know what to do. Can I initialize class ListResource in distant part of code and have Dependency injection of EntityManager working? Or somehow to get persistence context and then initialize this session bean?
I hope it makes sense. Its complicated problem for me to describe.