我想为JPA2创建一些可以在Java容器中运行的示例代码。
运行这些示例通常需要有一个Java服务器,但我想让事情变得更简单,并使用一个嵌入式容器+ maven来运行它们。
对于这种“项目”,哪一个更好?
Glassfish embedded,JBoss微容器还是OPENEJB?
其他人?
谢谢!
发布于 2011-02-17 18:13:06
在容器外部测试EJB的问题是不执行注入。我找到了这个解决方案。在无状态会话bean中,您有一个注释@PersistenceContext在独立的Java-SE环境中,您需要自己注入entitymanager,这可以在单元测试中完成。这是嵌入式服务器的快速替代方案。
@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();
}
}
单元测试实例化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();
}
}
}
https://stackoverflow.com/questions/5027003
复制相似问题