开发者

JPA2 samples embedded Java EE container?

开发者 https://www.devze.com 2023-02-12 03:08 出处:网络
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

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开发者_StackOverflow社区 "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();
        }
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消