简体   繁体   中英

JPA2 samples embedded Java EE container?

I want to create some sample code for JPA2 that can be run inside a Java EE container.

Running those sample normally require to have a Java EE server but i want to make things easier and to run them using an embedded container + maven.

Which one is better for this kind of "project" ?

Glassfish embedded , JBoss microcontainer or OPENEJB ?

Others ?

Thank you !

The problem to test EJB outside a container is that injections are not performed. I found this solution. In the stateless session bean you have an annotation @PersistenceContext in a standalone Java-SE environment you need to inject the entitymanager by yourself, whcih can be done in an unittest. This is a fast alternative to an emmbeded server.

@Stateless
public class TestBean implements TestBusiness {

    @PersistenceContext(unitName = "puTest")
    EntityManager entityManager = null;

    public List method() {
        Query query = entityManager.createQuery("select t FROM Table t");
        return query.getResultList();
    }
}

The unittest instantiates the entitymanager and 'injects' it into the bean.

public class TestBeanJUnit {

    static EntityManager em = null;
    static EntityTransaction tx = null;

    static TestBean tb = null;
    static EntityManagerFactory emf = null;

    @BeforeClass
    public static void init() throws Exception {
        emf = Persistence.createEntityManagerFactory("puTest");
    }

    @Before
    public void setup() {
        try {
            em = emf.createEntityManager();
            tx = em.getTransaction();
            tx.begin();
            tb =  new TestBean();
            Field field = TestBean.class.getDeclaredField("entityManager");
            field.setAccessible(true);
            field.set(tb, em);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @After
    public void tearDown() throws Exception {
        if (em != null) {
            tx.commit();
            em.close();
        }
    }

}

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