Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

Preciso recuperar um objeto do tipo T em minha classe DAO genérica.

O código que fiz é este e ele retorna erro de não ter encontrado objeto no banco.

public T findObject(String string) {
        EntityManager em = new JPAUtil().getEntityManager();
        return (T) em.createQuery("from "+ classe.getName() +" e where e.nome= '" + string + "'").getSingleResult();
   }

PS: Verifiquei no banco e o insert foi feito com sucesso.

Segue abaixo o erro:

nov 18, 2015 7:23:23 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{pessoaBean.retreiveCidadao}: javax.persistence.NoResultException: No entity found for query
javax.faces.FacesException: #{pessoaBean.retreiveCidadao}: javax.persistence.NoResultException: No entity found for query
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    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:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:164)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:164)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: javax.persistence.NoResultException: No entity found for query
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 25 more
Caused by: javax.persistence.NoResultException: No entity found for query
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:485)
    at dao.GenericDao.findObject(GenericDao.java:105)
    at controller.PessoaBean.retreiveCidadao(PessoaBean.java:79)
    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.apache.el.parser.AstValue.invoke(AstValue.java:262)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 26 more

nov 18, 2015 7:23:23 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/ProjetoWeb] threw exception [javax.persistence.NoResultException: No entity found for query] with root cause
javax.persistence.NoResultException: No entity found for query
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:485)
    at dao.GenericDao.findObject(GenericDao.java:105)
    at controller.PessoaBean.retreiveCidadao(PessoaBean.java:79)
    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.apache.el.parser.AstValue.invoke(AstValue.java:262)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    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:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:164)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:164)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

E as informações do Banco:

Hibernate: 
    alter table Agendamento 
        drop constraint FKh55aqhtigtfhqy5b2a4y91x2f
Hibernate: 
    alter table Esporte_Time 
        drop constraint FKii8teuxrgy0vx145q2meajf3t
Hibernate: 
    alter table Esporte_Time 
        drop constraint FKcon9lteq8urqkr7q89rt54tni
Hibernate: 
    alter table Programa_Public 
        drop constraint FKno6bbldosg8vq680bdtqg7pxi
Hibernate: 
    alter table Programa_Public_local 
        drop constraint FKkd9v3doomeyjyl9kef0cu95by
Hibernate: 
    alter table Programa_Public_local 
        drop constraint FK1mrlycotydmm1os489b88on1r
Hibernate: 
    alter table Programa_Public_Time 
        drop constraint FKpeqhb22h1dgbhefdni5sfsyxo
Hibernate: 
    alter table Programa_Public_Time 
        drop constraint FK7nj5gwydv3uymh2fk9glxdv2f
Hibernate: 
    alter table Time 
        drop constraint FK9ic1urn0lm29rrac7enkwspmb
Hibernate: 
    alter table Time_pessoa 
        drop constraint FKltwk2ueh9ex5tnmm8ybnjpqvh
Hibernate: 
    alter table Time_pessoa 
        drop constraint FKkd06xfvr9ycfil4s5sfgaf5ff
Hibernate: 
    drop table if exists Agendamento cascade
Hibernate: 
    drop table if exists Esporte cascade
Hibernate: 
    drop table if exists Esporte_Time cascade
Hibernate: 
    drop table if exists local cascade
Hibernate: 
    drop table if exists pessoa cascade
Hibernate: 
    drop table if exists Programa_Public cascade
Hibernate: 
    drop table if exists Programa_Public_local cascade
Hibernate: 
    drop table if exists Programa_Public_Time cascade
Hibernate: 
    drop table if exists Time cascade
Hibernate: 
    drop table if exists Time_pessoa cascade
Hibernate: 
    drop sequence hibernate_sequence
Hibernate: 
    create sequence hibernate_sequence start 1 increment 1
Hibernate: 
    create table Agendamento (
        id int8 not null,
        data timestamp,
        horaEntrada int4 not null,
        horaSaida int4 not null,
        minEntrada int4 not null,
        minSaida int4 not null,
        local_id int8,
        primary key (id)
    )
Hibernate: 
    create table Esporte (
        id int4 not null,
        modalidade varchar(255),
        nome varchar(255),
        numeroDeEsportistas int4 not null,
        primary key (id)
    )
Hibernate: 
    create table Esporte_Time (
        Esporte_id int4 not null,
        times_id int8 not null
    )
Hibernate: 
    create table local (
        Local_Type varchar(31) not null,
        id int8 not null,
        bairro varchar(255),
        cep varchar(255),
        disponivel boolean,
        nome varchar(255),
        numero varchar(255),
        rua varchar(255),
        zona varchar(255),
        preco float8,
        primary key (id)
    )
Hibernate: 
    create table pessoa (
        Pessoa_Type varchar(31) not null,
        ID int4 not null,
        cep varchar(255),
        cpf varchar(255),
        endereco varchar(255),
        municipio varchar(255),
        nome varchar(255),
        saldo float8 not null,
        cidadeDeOrigem varchar(255),
        tempoDePermanenciaEmDias int4,
        primary key (ID)
    )
Hibernate: 
    create table Programa_Public (
        ProgramaPublico_Type varchar(31) not null,
        id int8 not null,
        data timestamp,
        mandato varchar(255),
        nome varchar(255),
        verbaGasta float8 not null,
        taxaDeInscricao float8,
        vagasDisponiveis int4,
        esporte_id int4,
        primary key (id)
    )
Hibernate: 
    create table Programa_Public_local (
        Evento_id int8 not null,
        locais_id int8 not null
    )
Hibernate: 
    create table Programa_Public_Time (
        Campeonato_id int8 not null,
        timesInscritos_id int8 not null
    )
Hibernate: 
    create table Time (
        id int8 not null,
        nome varchar(255),
        esporte_id int4,
        primary key (id)
    )
Hibernate: 
    create table Time_pessoa (
        Time_id int8 not null,
        membros_ID int4 not null
    )
Hibernate: 
    alter table Agendamento 
        add constraint FKh55aqhtigtfhqy5b2a4y91x2f 
        foreign key (local_id) 
        references local
Hibernate: 
    alter table Esporte_Time 
        add constraint UK_l3qghy9h74lxl7xx0aw9kd5d unique (times_id)
Hibernate: 
    alter table Esporte_Time 
        add constraint FKii8teuxrgy0vx145q2meajf3t 
        foreign key (times_id) 
        references Time
Hibernate: 
    alter table Esporte_Time 
        add constraint FKcon9lteq8urqkr7q89rt54tni 
        foreign key (Esporte_id) 
        references Esporte
Hibernate: 
    alter table Programa_Public 
        add constraint FKno6bbldosg8vq680bdtqg7pxi 
        foreign key (esporte_id) 
        references Esporte
Hibernate: 
    alter table Programa_Public_local 
        add constraint UK_fe4kyccm7xutlud27ko5uwa4l unique (locais_id)
Hibernate: 
    alter table Programa_Public_local 
        add constraint FKkd9v3doomeyjyl9kef0cu95by 
        foreign key (locais_id) 
        references local
Hibernate: 
    alter table Programa_Public_local 
        add constraint FK1mrlycotydmm1os489b88on1r 
        foreign key (Evento_id) 
        references Programa_Public
Hibernate: 
    alter table Programa_Public_Time 
        add constraint UK_riqywk0oc9x3ki72gnhlwpe8 unique (timesInscritos_id)
Hibernate: 
    alter table Programa_Public_Time 
        add constraint FKpeqhb22h1dgbhefdni5sfsyxo 
        foreign key (timesInscritos_id) 
        references Time
Hibernate: 
    alter table Programa_Public_Time 
        add constraint FK7nj5gwydv3uymh2fk9glxdv2f 
        foreign key (Campeonato_id) 
        references Programa_Public
Hibernate: 
    alter table Time 
        add constraint FK9ic1urn0lm29rrac7enkwspmb 
        foreign key (esporte_id) 
        references Esporte
Hibernate: 
    alter table Time_pessoa 
        add constraint UK_2p4nah1ir5rjbrdwsgc4elqyc unique (membros_ID)
Hibernate: 
    alter table Time_pessoa 
        add constraint FKltwk2ueh9ex5tnmm8ybnjpqvh 
        foreign key (membros_ID) 
        references pessoa
Hibernate: 
    alter table Time_pessoa 
        add constraint FKkd06xfvr9ycfil4s5sfgaf5ff 
        foreign key (Time_id) 
        references Time
Hibernate: 
    select
        nextval ('hibernate_sequence')
Hibernate: 
    insert 
    into
        pessoa
        (cep, cpf, endereco, municipio, nome, saldo, Pessoa_Type, ID) 
    values
        (?, ?, ?, ?, ?, ?, 'cidadao', ?)
Hibernate: 
    select
        cidadao0_.ID as ID2_4_,
        cidadao0_.cep as cep3_4_,
        cidadao0_.cpf as cpf4_4_,
        cidadao0_.endereco as endereco5_4_,
        cidadao0_.municipio as municipi6_4_,
        cidadao0_.nome as nome7_4_,
        cidadao0_.saldo as saldo8_4_ 
    from
        pessoa cidadao0_ 
    where
        cidadao0_.Pessoa_Type='cidadao' 
        and cidadao0_.nome='1'

Acontece que todos os meus Id podem ser convertidos para String. Entretanto, todos os métodos do DAO consideram Id's como Integer, inclusive o find do EntityManager.

4 respostas

Oi Douglas,

A exception é que não encontrou a Entidade, é porque você utilizou o método getName de Class, ele retorna o caminho do pacote junto ao nome da classe, troque para o método getSimpleName.

Retornou o mesmo erro.

solução!

E assim?

    public T findObject(String string) {
        EntityManager em = new JPAUtil().getEntityManager();
        Query query = em.createQuery("from " + classe.getSimpleName() + " e where e.nome = :nome");
        query.setParameter("nome", string);
        return (T) query.getSingleResult();
    }

Resolvi esse problema. Isso funcionou!!! Mas infelizmente eu tinha problemas na minha modelagem e estou precisando refazer.