简体   繁体   中英

calling EJB3 session bean from a webservice EJB3 session bean causing entity manager null

Ok I have a scenario here, and I want a standard solution, basically I have exposed EJBsession3 beans as my webservice on the server side and they further call the EJBsession3 bean to execute DAO methods. see below is the sample Code.

//This is a EJB3 session bean and I am using container managed jta transactions 
@Stateless
public class datatypes implements datatypesRemote {

@PersistenceContext(unitName = "EJBtest")
EntityManager entityManager;


public List<Datatype> retrieveAllDatatypes(int targetSystemId,EntityManager ent)
        throws RuntimeException {
    String q = "SELECT oneDatatype from " + Datatype.class.getName()
            + " oneDatatype "
            + "where oneDatatype.targetSystem.targetSystemId = "
            + targetSystemId;

    //entityManager=ent;
    Query query = entityManager.createQuery(q);


    System.out.println("Query retrieveAll" + q);
    @SuppressWarnings("unchecked")
    List<Datatype> templates = query.getResultList();
    return templates;
}

}

The class above is basically my DAO class that will handle queries now below is my web services class

 @WebService(serviceName="backend")
    @Stateless
    public class backEndForm implements backEndFormRemote {
    //@PersistenceContext(name = "EJBtest")
    //EntityManager entityManager;

   private datatypesRemote data= new datatypes();

        public List<Datatype> retrieveAllDatatypes(int id){      
            //entityManager.clear();
            data=new datatypes();
            return  data.retrieveAllDatatypes(id,null);
        }
    }

Now the Issue is like this my web client calls my web service method and that method further calls the DAO methods that will fetch the data from data base and return to the web service and web service will return data to the requesting client But when I execute my SQL query the entity manager is null I don't know why so a non standard solution I developed is to pass the entity manager from the web services class to the DAO class, as you can see in the sample code which is commented out.

So my question, is there any other Standard way to do it ? why the entity manager is null in the second ejb3 bean and not in the first ejb3 bean ?

Injection does not happen when you create objects with the new operator. You need to let your container create the datatypes bean and inject it into your backEndForm :

@WebService(serviceName="backend")
@Stateless
public class backEndForm implements backEndFormRemote {

    @EJB
    private datatypesRemote data;

    public List<Datatype> retrieveAllDatatypes(int id){      
        return  data.retrieveAllDatatypes(id,null);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM