Domanda

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.

È stato utile?

Soluzione

If you have a web service and a standalone app calling the same bean, I would recommend you to move the functionality in a separate stateless bean and create remote and local interfaces to it. This way you can inject local bean into you web service bean, and call the remote one with jndi.

More about accessing Java EE beans here.

Alternatively, your client java code can call the web service to get all the data. Refer to this question about ways to connect to a RESTful service.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top