繁体   English   中英

JPA2示例嵌入了Java EE容器?

[英]JPA2 samples embedded Java EE container?

我想为JPA2创建一些可以在Java EE容器中运行的示例代码。

运行这些示例通常需要具有Java EE服务器,但我希望使事情更容易,并使用嵌入式容器+ maven运行它们。

对于这种“项目”哪一种更好?

Glassfish嵌入式,JBoss微容器或OPENEJB?

其他 ?

谢谢 !

在容器外测试EJB的问题是不执行注入。 我找到了这个解决方案 在无状态会话bean中,您在独立的Java-SE环境中有一个注释@PersistenceContext,您需要自己注入实体管理器,这可以在单元测试中完成。 这是嵌入式服务器的快速替代方案。

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM