前文使用容器管理 EntityManager(由 EJB 容器建立、生命週期全管)。Servlet 中需改用應用程式管理模式:透過 EntityManagerFactory.createEntityManager() 手動建立,用畢關閉。
persistence-unit 的 transaction-type="RESOURCE_LOCAL"(非 JTA)。jta-data-source 改為 non-jta-data-source(值不變)。此模式下不可使用 @PersistenceContext 讓容器自動注入,若需容器管理可另定義持久化單元。
public class MyServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myentity");
EntityManager em = emf.createEntityManager();
DateBean db = em.find(DateBean.class, 1);
resp.getWriter().println(db.getMyDate());
em.close();
emf.close();
}
}
關鍵點:手動建立 EMF/EM、執行查詢、必須成對關閉 避免資源洩漏。