JPA2 samples embed Java EE container?

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

Running this sample usually requires a Java EE server, but I want to simplify the task and run them using the built-in + maven container.

Which one is better for such a "project"?

Integrated glass panel, JBoss or OPENEJB microcontainer?

Others?

Thank!

+3
source share
1 answer

EJB , . . bean @PersistenceContext Java-SE entitymanager, unittest. .

@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();
    }
}

Unittest entitymanager 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();
        }
    }

}
+3

Source: https://habr.com/ru/post/1792746/


All Articles