2
respostas

CDI: DAO E TypedQuery

Olá

Estou com um problema á um certo tempo e não estou conseguindo resolver de forma á manter as boas práticas. Preciso fazer um ClienteBean e nele gostaria de ter a lista de medidas porém através de HQL , achei melhor criar um medida DAO para ter um especialista em Medidas e nele ter um TypedQuery, porém fica dando erro Session is closed!. Já tentei até incluir o TypedQuery dentro de ClienteBean mas dá o mesmo erro.

@ViewModel
public class ClienteBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private DAO<Cliente,Integer> clienteDao;
    private MedidaDao medidaDao;

    private Cliente cliente;

    private List<Cliente> clientes;
    private List<Medida> clienteMedidas;

    @Inject
    public ClienteBean(DAO<Cliente,Integer> clienteDao, MedidaDao medidaDao){
        this.clienteDao = clienteDao;
        this.medidaDao = medidaDao;
    }

    @PostConstruct
    public void postConstruct(){
        this.clientes = clienteDao.listaTodos();
    }

    public void carregar(Cliente cliente) {
        this.cliente = cliente;
        clienteMedidas = medidaDao.medidasCliente(cliente);
    }

 }

public class MedidaDao implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject @Query("select m from Medida m, Cliente c Where c.id = 1")
    private TypedQuery<Medida> query;

    public List<Medida> medidasCliente(Cliente cliente) {        

        try {
            if(cliente!=null){
                //query.setParameter("pClienteId", cliente.getId());
                return query.getResultList();
            } else {
                return null;
            }
        } catch (NoResultException ex) {
            ex.printStackTrace();
            return null;
        }

    }

}

ERRO:
ADVERTÊNCIA: /cliente.xhtml @33,171 actionListener="#{clienteBean.carregar(cliente)}": javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!
javax.el.ELException: /cliente.xhtml @33,171 actionListener="#{clienteBean.carregar(cliente)}": javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIData.broadcast(UIData.java:1108)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:266)
    at br.morica.dao.MedidaDao.medidasCliente(MedidaDao.java:26)
    at br.morica.bean.ClienteBean.carregar(ClienteBean.java:42)
    at br.morica.bean.ClienteBean$Proxy$_$$_WeldSubclass.carregar(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 30 more
Caused by: org.hibernate.SessionException: Session is closed!
    at org.hibernate.internal.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:129)
    at org.hibernate.internal.SessionImpl.getPersistenceContext(SessionImpl.java:1891)
    at org.hibernate.internal.AbstractQueryImpl.isReadOnly(AbstractQueryImpl.java:214)
    at org.hibernate.internal.AbstractQueryImpl.getQueryParameters(AbstractQueryImpl.java:933)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:257)
    ... 42 more
2 respostas

Fala aí Antonio como está o seu produtor de TypedQuery e o de EntityManager?

Olá Fernando

Estou mantendo o mesmo do exemplo do curso:

@SuppressWarnings("unchecked")
public class DAOFactory {

    @Inject
    private EntityManager manger;

    @Produces
    public <T,I> DAO<T,I> factory(InjectionPoint point){

        ParameterizedType type = (ParameterizedType) point.getType();

        Class<T> classe = (Class<T>) type.getActualTypeArguments()[0];
        return new DAO<T,I>(classe, manger);
    }

}
public class TypedQueryFactory {

    @Inject
    private EntityManager em;

    @Produces
    @Query("")
    public <X> TypedQuery<X> factory(InjectionPoint point){

        ParameterizedType type = (ParameterizedType) point.getType();

        @SuppressWarnings("unchecked")
        Class<X> classe = (Class<X>) type.getActualTypeArguments()[0];

        String jpql = point.getAnnotated().getAnnotation(Query.class).value();
        return em.createQuery(jpql, classe);
    }

}

Obrigado AFP