Quando no DAO tento pegar o EntityManager ele vem como null, sei que isso acontece porque o escopo não está como request, mas gostaria de saber como faço para resolver esse problema porque jaá procurei bastante e não achei nada.
Código do Filtro:
[code]@WebFilter(urlPatterns="/*")
public class FilterJPATransaction implements Filter {
private EntityManagerFactory emf;
@Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
EntityManager em = emf.createEntityManager();
request.setAttribute("entityManager", em);
request.setCharacterEncoding("UTF-8"); //para problemas com acentuação
response.setCharacterEncoding("UTF-8");
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
chain.doFilter(request, response); //dentro do try para capturar as exceções dos Beans
tx.commit();
} catch (Throwable e) {
if(tx != null && tx.isActive()){
tx.rollback();
e.printStackTrace();
}
}finally{
em.close();
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.emf = Persistence.createEntityManagerFactory("Igreja");
}
@Override
public void destroy() {
this.emf.close();
}
}[/code]
Métudo Utilizado para pegar o EntityManager setado no request:
[code]public static EntityManager getEntityManagerByFacesContext() {
ELContext el = FacesContext.getCurrentInstance().getELContext();
return (EntityManager) FacesContext.getCurrentInstance()
.getApplication().getELResolver()
.getValue(el, null, "entityManager");
}[/code]