hibernate通过SessionFactory管理实体类对数据库的操作,JPA通过EntityManagerFactory产生EntityManager操作数据库中的实体类,我们可以对session进行延迟加载,同样也可以对entityManager进行延迟加载,只需要写一个过滤EntityManager的Filter,就可以将entitymanager延长到JSP页面,具体代码如下:
public class OpenEntityManagerFilter implements Filter {
private static EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> tl = new ThreadLocal<EntityManager>();;
public void destroy() {
// TODO Auto-generated method stub
if(emf!=null){
emf.close();
System.out.println("销毁EntityManagerFactory");
}
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
arg2.doFilter(arg0, arg1);
EntityManager em = tl.get();
tl.set(null);
if(em!=null){
em.close();
System.out.println("关闭EntityManager");
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
emf = Persistence.createEntityManagerFactory("JpaTemp");
}
public static EntityManager getEntityManager()
{
EntityManager em = tl.get();
if(em==null||!em.isOpen())
{
em = (emf!=null)?emf.createEntityManager():null;
tl.set(em);
System.out.println("打开EntityManager");
}
return em;
}
}
需要注意的是persistence.xml文件位于src目录下的META-INF目录,并且设置事务类型为RESOURCE_LOCAL,不是JTA,当项目启动时,会自动加载数据库连接和JPA中实体类,并创建EntityManagerFactory