mushroom
mushroom

Reputation: 1945

Getting the EntityManager from an Embedded EJBContainer

How do I get the EntityManager from an instantiated EJBContainer (OpenEJB)?

I have tried using the @PersistenceContext annotation but it does not work.

Upvotes: 1

Views: 550

Answers (2)

Torsten Römer
Torsten Römer

Reputation: 3926

I am not sure if your question is about a unit test but this works for me:

A "helper bean" in the (test) package:

@Stateless
public class EntityManagerProvider {

    @PersistenceContext(unitName = "pu-name")
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }
}

then look up that bean with the EJBContainer and get the EntityManager:

private EntityManager getEntityManager() throws NamingException {
    final EntityManagerProvider provider = (EntityManagerProvider)ejbContainer.getContext()
            .lookup("java:global/testproject/EntityManagerProvider");

    return provider.getEntityManager();
}

Upvotes: 0

Petr Mensik
Petr Mensik

Reputation: 27496

Yes, because you are not running Unit tests in EJB container. So either you have to mock the EntityManager (for example with Mockito) or I would suggest you using Arquillian which will allow to run your tests in reall container (which can be already running on some server or you can start it by yourself within the tests).

There is a nice tutorial on their Guides page on testing JPA so check it out :) Testing Java Persistence

Upvotes: 1

Related Questions