protected EntityManager em;
上面的代码需要放在任意一个SessionBean的类中,EJB容器会自动创建EntityManager对象。但如果要在Servlet中直接访问EntityManager对象,需要使用EntityManagerFactory接口的createEntityManager方法来创建EntityManager对象,在使用完EntityManagerFactory和EntityManager对象后,可以使用相应的close方方关闭这两个对象。在编写Servlet中访问应用程序管制实体Bean之前,需要修改一个persistence.xml文件的内容,修改后的结果如下:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns: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:/MyPIM</non-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. 将<persistence-unit>元素的transaction-type属性值设为RESUORCE_LOCAL。
2, 将<jta-data-source>元素改成<non-jta-data-source>,元素值不变。
要注意,这时不能使用@PersistenceContext注释通知EJB容器自动创建EntityManager对象了,如果仍然想这样做,可以定义其他的<persistence-unit>元素。
下面是访问EntityManager对象的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();
}
}