在前面的文章中使用的都是容器管制的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方方關閉這兩個對象。在編寫Servlet中訪問應用程序管制實體Bean之前,需要修改一個persistence.XML文件的內容,修改後的結果如下:
- < XML version="1.0" encoding="UTF-8"?>
- < persistence XMLns="http://Java.sun.com/XML/ns/persistence"
- < XMLns:xsiXMLns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://Java.sun.com/XML/ns/persistence
- http://Java.sun.com/XML/ns/persistence/persistence_1_0.xsd"
- version="1.0">
- < persistence-unit name="myentity" transaction-type="RESOURCE_LOCAL">
- < non-jta-data-source>Java:/MyPIMnon-jta-data-source>
- < propertIEs>
- < property name="hibernate.hbm2ddl.auto" value="none" />
- < property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
- < property name="hibernate.format_sql" value="true" />
- < property name="hibernate.show_sql" value="true" />
- < propertIEs>
- < persistence-unit>
- < persistence>
修改的地方有如下兩個:
1. 將元素的transaction-type屬性值設為RESUORCE_LOCAL。
2, 將元素改成,元素值不變。
要注意,這時不能使用@PersistenceContext注釋通知EJB容器自動創建EntityManager對象了,如果仍然想這樣做,可以定義其他的元素。
下面是訪問EntityManager對象的Servlet代碼:
- package servlet;
- import Java.io.IOException;
- import Javax.persistence.EntityManager;
- import Javax.persistence.EntityManagerFactory;
- import Javax.persistence.Persistence;
- import Javax.persistence.PersistenceContext;
- import Javax.servlet.ServletException;
- import Javax.servlet.http.HttpServlet;
- import Javax.servlet.http.HttpServletRequest;
- import Javax.servlet.http.HttpServletResponse;
- import entity.DateBean;
- public class MyServlet extends HttpServlet
- {
- private static final long serialVersionUID = 1L;
- protected void service(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException
- {
- EntityManagerFactory emf = Persistence.createEntityManagerFactory("myentity");
- EntityManager newEM = emf.createEntityManager();
- DateBean db = newEM.find(DateBean.class, 1);
- response.getWriter().println(db.getMyDate());
- newEM.close();
- emf.close();
- }
- }