Home > OS >  EntityManager injected only once if declared into two different EJBs
EntityManager injected only once if declared into two different EJBs

Time:08-24

I am on Weblogic 12c JPA/Hibernate EJB 3.

I wish to simplify my class model as follow:

public abstract class AbstractEJBBean {

  @PersistenceContext(unitName = "myPU")
  private EntityManager entityManager;

}

@Local
public interface FirstEJB {
    void someMethod1();
}

@Stateless
public class FirstEJBImpl extends AbstractEJBBean implements FirstEJB {

    @Override
    public void someMethod1() {
        // Here entityManager has been injected.
    }

}

@Local
public interface SecondEJB {
    void someMethod2();
}

@Stateless
public class SecondEJBImpl extends AbstractEJBBean implements SecondEJB {

    @Override
    public void someMethod2() {
        // Here entityManager has NOT been injected!!!
    }

}

In such situation, Weblogic starts (no errors logged), the application starts, but: only then entity manager into FirstEJBImpl instance have been injected. The one inside SecondEJBImpl is null!!!

I never seen any like this.

Could somebody tell my why and how to avoid it?

Thank you so much!!!

CodePudding user response:

I found the solution on my own.

I suppose it is a Weblogic bug, but I am not so sure, but my solution works as expected.

I had to remove the abstract base class and inject the entity manager directly inside each EJB.

@Local
public interface FirstEJB {
    void someMethod1();
}

@Stateless
public class FirstEJBImpl implements FirstEJB {

    @PersistenceContext(unitName = "myPU")
    private EntityManager entityManager;

    @Override
    public void someMethod1() {
        // Here entityManager has been injected.
    }

}

@Local
public interface SecondEJB {
    void someMethod2();
}

@Stateless
public class SecondEJBImpl implements SecondEJB {

    @PersistenceContext(unitName = "myPU")
    private EntityManager entityManager;

    @Override
    public void someMethod2() {
        // Here entityManager has been injected too! :)
    }

}
  • Related