【问题标题】:JPA2 samples embedded Java EE container?JPA2 示例嵌入式 Java EE 容器?
【发布时间】:2011-06-28 23:02:03
【问题描述】:

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

运行这些示例通常需要一个 Java EE 服务器,但我想让事情变得更简单,并使用嵌入式容器 + maven 来运行它们。

这样的“项目”,哪一个比较好?

Glassfish 嵌入式、JBoss 微容器还是 OPENEJB?

其他?

谢谢!

【问题讨论】:

    标签: java jpa jakarta-ee jpa-2.0


    【解决方案1】:

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

    @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 使用的应用程序。
    猜你喜欢
    • 2011-04-25
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    相关资源
    最近更新 更多