Alguém consegiu contornar open session in view ao trabalhar com JPA? Poderia compartilhar?
Estou tendo o famoso "LazyInitializationException", e encontrei diversas soluções porém todas ligadas ao hibernate.
Sendo assim eu teria que implementar o "HibernateUtil" para pegar o session, ficando asssim amarrado ao hibernate..
Ou utilizar algum framework como Spring ou Eclipse Link para controlar o opem session in view. me corrijam se estiver errado..
Estou fazendo assim atualmente..
Salvo um objeto.getEm().merge(paciente);
getEm().flush();
public EntityManager getEm() {
ELContext el = FacesContext.getCurrentInstance().getELContext();
return (EntityManager) FacesContext.getCurrentInstance()
.getApplication().getELResolver()
.getValue(el, null, "entityManager");
}
public class FiltroJPA implements Filter {
private EntityManagerFactory factory;
@Override
public void destroy() {
this.factory.close();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException,PersistenceException
{
EntityManager entityManager = this.factory.createEntityManager();
request.setAttribute("entityManager", entityManager);
entityManager.getTransaction().begin();
chain.doFilter(request, response);
try {
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.factory = Persistence.createEntityManagerFactory("jpa");
}
Aceito sugestões :D