mardi 2 juin 2015

Java - EJB Equivalent of EntityManagerProvider in Spring

I've been banging my head on the wall for the past couple of days trying to get this to work but I've not been able to.

I wrote a JPA EntityManagerProvider recently using EJB:

EntityManagerProviderBean.java

@Stateless
public class EntityManagerProviderBean {

    @PersistenceContext(unitName="PU1")
    private EntityManager entityManager1;   

    @PersistenceContext(unitName="PU2")
    private EntityManager entityManager2;

    public EntityManager getEntityManager() {
        return (...) ? entityManager1: entityManager2;
    }
}

And then of course I can inject the EJB wherever needed like this:

UserFacade.java

@Stateless
public class UserFacade {

    @EJB
    private EntityManagerProviderBean emProvider;
    private EntityManager em = emProvider.getEntityManager();

    ...
}

Now I'm trying to do something similar using Spring, using annotations, and without doing anything in XML. I can't seem to figure out a way to inject the EntityManager. Anything that I do leads to a NullPointerException. For example, I tried to inject the EntityManager manually without relying on my EntityManagerProviderBean, like this:

UserFacadeSpring.java

public class UserFacadeSpring {

    @PersistenceContext(unitName="PU1")
    private EntityManager em;

    ...
}

But this gives me a NullPointerException. So the EntityManager is not being injected at all and I'm not sure what's wrong.

So two questions basically:

  1. How can I inject the EntityManager using Spring?
  2. How can I use my existing EntityManagerProviderBean EJB in Spring? What modifications do I need to make?

Any help in this matter will be greatly appreciated. As you can tell I'm a complete noob to Spring. I tried to read the guide but everything's flying over my head at the moment. I actually did try to do something half-baked but it didn't work either (I either get NullPointerException or BeanNotFoundException, I must have used every combination of @Component, @Bean, @Autowired annotations I think!):

EntityManagerProviderSpring.java

@Component
public class EntityManagerProviderSpring {

    @PersistenceContext(unitName="PU1")
    private EntityManager entityManager1;   

    @PersistenceContext(unitName="PU2")
    private EntityManager entityManager2;

    @Bean
    public EntityManager getEntityManager() {
        return (...) ? entityManager1: entityManager2;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(EntityManagerProviderSpring.class);
    EntityManagerProviderSpring emProvider = context.getBean(EntityManagerProviderSpring.class);
    EntityManager em = emProvider.getEntityManager();

    ...
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire