摘要: 在前面的文章中使用的都是容器管制的EntityManager對象。這類EntityManager對象是由EJB容器創建的,在這種情況下,EntityManager對象的生命周期完全由EJB容器來管理。在SessionBean中可以使用如下的代碼來通知EJB容器創建 EntityManager對象:
@PersistenceContext(unitName="myentity")
protected EntityManager em;
上面的代碼需要放在任意一個SessionBean的類中,EJB容器會自動創建EntityManager對象。但如果要在Servlet中直接訪問 EntityManager對象,需要使用EntityManagerFactory接口的createEntityManager方法來創建 EntityManager對象,在使用完EntityManagerFactory和EntityManager對象后,可以使用相應的close方方關閉這兩個對象。
閱讀全文