Problem with controlling connections with the Bank

Asked

Viewed 39 times

1

I am having some problems connecting to the database. Follow my code and the exception.

Code

@Repository
public class MinhaClasseDAOImpl implements MinhaClasseDAO{

protected EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence_banco");

protected EntityManager entityManager;

protected EntityManager getEntityManager() {
    if(!entityManagerFactory.isOpen()){
        entityManagerFactory = Persistence.createEntityManagerFactory("persistence_banco");
    }
    return entityManagerFactory.createEntityManager();
}

public List<MinhaClasse> recuperarTotalMinhaClasse(int idTipoMinhaClasse, List<String> listaData){
    List<MinhaClasse> listaMinhaClasse = new ArrayList<MinhaClasse>();
    try{
        entityManager = getEntityManager();
        entityManager.getTransaction().begin();
        for(String data:listaData){
            String sql = "select sum(total), "
                    + "sum(quantidadeAguardou), sum(quantidadeNaoIdentificada), "
                    + "sum(quantidadeTeclouZero), sum(quantidadeTeclouZeroAguardou), "
                    + "sum(quantidadeTransferidaBC) "
                    + "from MinhaClasse where id_tipo_MinhaClasse = :idTipoMinhaClasse ";
                    if(data.length() == 10){
                        sql += "and data = :data";
                    }else{
                        sql += "and MONTH(data) = MONTH(:data) "
                                + "and YEAR(data) = YEAR(:data)";
                    }

            Query query = entityManager.createQuery(sql,Object[].class);
            query.setParameter("idTipoMinhaClasse", idTipoMinhaClasse);
            if(data.length() == 10){
                query.setParameter("data", DataUtil.converter(data));
            }else{
                query.setParameter("data", DataUtil.converter("01/"+data));
            }
            Object[] retorno = (Object[]) query.getSingleResult();
            MinhaClasse MinhaClasse = new MinhaClasse();
            if(retorno != null){
                MinhaClasse.setTotal(retorno[0]==null?0:Math.toIntExact((Long)retorno[0]));
                MinhaClasse.setQuantidadeAguardou(retorno[1]==null?0:Math.toIntExact((Long)retorno[1]));
                MinhaClasse.setQuantidadeNaoIdentificada(retorno[2]==null?0:Math.toIntExact((Long)retorno[2]));
                MinhaClasse.setQuantidadeTeclouZero(retorno[3]==null?0:Math.toIntExact((Long)retorno[3]));
                MinhaClasse.setQuantidadeTeclouZeroAguardou(retorno[4]==null?0:Math.toIntExact((Long)retorno[4]));
                MinhaClasse.setQuantidadeTransferidaBC(retorno[5]==null?0:Math.toIntExact((Long)retorno[5]));
                MinhaClasse.setPerfil(data);
            }
            listaMinhaClasse.add(MinhaClasse);
        }
    }catch(Exception ex){
        System.out.println("Erro ao recuperar MinhaClasse");
        ex.printStackTrace();
    }finally {
        fecharConexao();
    }
    return listaMinhaClasse;
}

private void fecharConexao(){
    if (entityManager.isOpen()){
        entityManager.close();
    }
}
}

Exception

Erro ao recuperar MinhaClassejava.lang.IllegalStateException: EntityManager is closed

at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:105)
at org.hibernate.jpa.spi.BaseQueryImpl.checkOpen(BaseQueryImpl.java:103)
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:617)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:180)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49)
at com.everis.dao.impl.MinhaClasseDAOImpl.recuperarTotalMinhaClasse(MinhaClasseDAOImpl.java:58)
at com.everis.service.impl.MinhaClasseServiceImpl.listarHistoricoMinhaClasse(MinhaClasseServiceImpl.java:59)
at com.everis.ws.MinhaClasseWS.listarHistoricoMinhaClasse(MinhaClasseWS.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

1 answer

1

This part of the code is useless as you already make the opening statement of the EntityManagerFactory once. Delete it.

if(!entityManagerFactory.isOpen()){
    entityManagerFactory = Persistence.createEntityManagerFactory("persistence_banco");
}

Add this line directly to Finally and delete the method fecharConexao(), because it is closing the wrong entityManager probably.

entityManager.close();

Finally add the line below at the end of your block try{}

entityManager.getTransaction().commit();

I still think this should not solve the problem, please inform me which line 58 of your code is where the error happens.

And go to divide your code better, you make the opening of EntityManagerFactory in the same class that receives the data and that also accesses the database. This may not be the cause of this problem, but it will cause you a headache in the future. I suggest creating classes FabricaDeConexao, SuaEntidade and SuaEntidadeDAO.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.