3
我想爲JPA2創建一些可以在Java EE容器內運行的示例代碼。JPA2示例嵌入式Java EE容器?
運行這些示例通常需要有一個Java EE服務器,但我想使事情更容易,並使用嵌入容器+ maven運行它們。
哪一個更適合這種「項目」?
Glassfish embedded,JBoss microcontainer或OPENEJB?
其他?
謝謝!
我想爲JPA2創建一些可以在Java EE容器內運行的示例代碼。JPA2示例嵌入式Java EE容器?
運行這些示例通常需要有一個Java EE服務器,但我想使事情更容易,並使用嵌入容器+ maven運行它們。
哪一個更適合這種「項目」?
Glassfish embedded,JBoss microcontainer或OPENEJB?
其他?
謝謝!
在容器外測試EJB的問題是不執行注入。我發現這個解決方案。在無狀態會話bean中,您需要在獨立的Java-SE環境中註釋@PersistenceContext ,您需要自己注入entitymanager,這可以在unittest中完成。這是emmbeded服務器的快速替代方案。
@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();
}
}
}
感謝您的回答。它有幫助。這更適用於測試一些代碼。我想要做的是實際運行一些應用程序,這些應用程序將演示如何使用JPA2。 – Cris 2011-02-17 13:00:58