Order By Hibernate in JSF

Asked

Viewed 185 times

0

Hello, good afternoon, I am a beginner in this web world and I need to order establishments by punctuation (the best punctuated at the beginning, LOGICAL)

The mistake is An Error Occurred: java.lang.NullPointerException

Here’s my entity, any help is welcome

public class Estabelecimento implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
@Column
String nome;
String cnpj;
String cidade;
String bairro;
String rua;
String numero;
String telefone;
int pontos;

Here the Bean Code

public List listaEstabelecimentosPontos(){
  listaEstabelecimentos =  estabelecimentoDao.ordenarPontos();
  return this.listaEstabelecimentos;
}

And here the xml

<?xml version="1.0" encoding="UTF-8"?>

<ui:define name="content">
    <h:form>
        <p:dataTable var="tabela" value="#{estabelecimentosBean.listaEstabelecimentosPontos()}">
        <p:column headerText="Id">
            <h:outputText value="#{tabela.id}" />
        </p:column>

        <p:column headerText="nome">
            <h:outputText value="#{tabela.nome}" />
        </p:column>

        <p:column headerText="cnpj">
            <h:outputText value="#{tabela.cnpj}" />
        </p:column>

        <p:column headerText="cidade">
            <h:outputText value="#{tabela.cidade}" />
        </p:column>

        <p:column headerText="bairro">
            <h:outputText value="#{tabela.bairro}" />
        </p:column>

        <p:column headerText="rua">
            <h:outputText value="#{tabela.rua}" />
        </p:column>

        <p:column headerText="numero">
            <h:outputText value="#{tabela.numero}" />
        </p:column>

        <p:column headerText="telefone">
            <h:outputText value="#{tabela.telefone}" />
        </p:column>

        <p:column headerText="AÇÕES">
              <center>
              <p:commandButton value="Remover" action="#{estabelecimentosBean.removerEstabelecimento(tabela)}" />
              <p:commandButton value="Editar" action="#{estabelecimentosBean.atualizarEstabelecimento(tabela)}" />
              </center>
        </p:column>

     </p:dataTable>
  </h:form>
</ui:define>

Error log

java.lang.NullPointerException
at br.com.fastchoice.DAO.EstabelecimentoDAO.ordenarPontos(EstabelecimentoDAO.java:37)
at br.com.fastchoice.bean.EstabelecimentosBean.listaEstabelecimentosPontos(EstabelecimentosBean.java:30)
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 javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:732)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:759)
at javax.faces.component.UIData.getRowCount(UIData.java:356)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:806)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:788)
at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:281)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:243)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:85)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:49)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)

DAO class

public class EstabelecimentoDAO {

Session sessao;
Transaction trans;
List<Estabelecimento> list;

public List<Estabelecimento> getList() {
    sessao = HibernateUtil.getSessionFactory().openSession();
    trans = sessao.beginTransaction();
    Criteria cri = sessao.createCriteria(Estabelecimento.class);
    this.list = cri.list();
    return list;

}

public List<Estabelecimento> ordenarPontos() {
    String jpql = "SELECT * FROM Estabelecimento estabelecimento ORDER BY estabelecimento.pontos DESC";
    return sessao.createQuery(jpql).getResultList();
}/**/


public void adicionarEstabelecimento(Estabelecimento es) {
    try {
        sessao = HibernateUtil.getSessionFactory().openSession();
        trans = sessao.beginTransaction();

        Estabelecimento estabelecimento = new Estabelecimento();
        estabelecimento.setCnpj(es.getCnpj());
        estabelecimento.setNome(es.getNome());

        estabelecimento.setCidade(es.getCidade());
        estabelecimento.setBairro(es.getBairro());
        estabelecimento.setRua(es.getRua());
        estabelecimento.setNumero(es.getNumero());
        estabelecimento.setTelefone(es.getTelefone());
        estabelecimento.setPontos(es.getPontos());
        sessao.save(estabelecimento);
        trans.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sessao.close();
    }
}

public void removerEstabelecimento(Estabelecimento es) {

    try {
        sessao = HibernateUtil.getSessionFactory().openSession();
        trans = sessao.beginTransaction();

        sessao.delete(es);
        trans.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sessao.close();
    }

}

public void editarEstabelecimento(Estabelecimento es) {

    try {
        sessao = HibernateUtil.getSessionFactory().openSession();
        trans = sessao.beginTransaction();

        sessao.update(es);
        trans.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sessao.close();
    }

}

}

  • You can post your query as well?

  • I did it in the Establishment class, right? http://pastebin.com/R3dsSwXW

  • David, you can click [Dit] and add this information to your question. This will be very visible to others who come to try to help you. I also recommend you to do the [tour], read [Ask] and how to create a minimum, complete and verifiable example

  • Pastebin is also not a good idea. A lot of people have blocked access to certain websites. Edit your question and put the code on it.

  • Okay, edited, I’m sorry, I’m new to this forum system

  • Relax, the start is a bit confusing indeed. But soon you will be able to use the site quietly. Your question is much better now, just to highlight the [en.so] is not a forum.

  • Is your query a typedquery? The error is saying that you expect a string, but a string and a class are being passed. Try to leave only the jpql string by removing the Establishment class.

  • I edited the question, now the mistake is another

  • Can you put the error stack, please? A log only line is insufficient for better analysis. So we can know where the error is occurring.

  • Ready, I put

Show 5 more comments

1 answer

0


Well, right here in this piece of code:

public List<Estabelecimento> ordenarPontos() {
    String jpql = "SELECT * FROM estabelecimentos ORDER BY pontos DESC";
    return sessao.createQuery(jpql).list();
}

you are searching with wrong parameters.

The right thing would be:

public List<Estabelecimento> ordenarPontos() {
    sessao = HibernateUtil.getSessionFactory().openSession();
    trans = sessao.beginTransaction();
    String jpql = "SELECT estabelecimento FROM Estabelecimento estabelecimento ORDER BY estabelecimento.pontos DESC";
    return sessao.createQuery(jpql).list();
}

I hope I’ve helped.

Abs

  • Hi Weslley, I am using Mysql and tested this code above, it appears an error message Error Code: 1146. Table 'fastchoice.establishment' doesn’t exist

  • There is a difference between SQL code and JPQL @Davidfilipe. If you create queries within your code using hibernate, you should use JPQL, not SQL. Try to put the method I put in my answer in your code and run your project. I await your feedback.

  • Still the error java.lang.Nullpointerexception, can I give you the project on github? I think it would be better for better analysis

  • Watch my edit. Abs

  • getResultList is giving error cannot find Symbol

  • Please edit your question by posting the code that contains the object class sessao in your code.

  • Okay, I edited, I can’t post my Miles

  • All right. I edited the answer again. Make sure that the way it is now, your problem is solved. Abs

  • Now is another error An Error Occurred: Unexpected token: * near line 1, column 8 [SELECT * FROM br.com.fastchoice.entity.Establishment establishment ORDER BY establishment.DESC points] kkk is complicated

  • I edited the answer again. PS: I have no IDE here to test, I’m at a friend’s house and borrowed his PC to help you.

  • FOOOOOOOOOOOOOOOOOOOOOI, my GOD, thank you very much man, but really, this little of your time that you stopped to help me, Please, you don’t realize how much I’ve broken my head with 'this bullshit'' thank you very much, man, 4 days ago I said I was in need of help in the project and teacher just visualizes and does not respond, want you implement something that besides not teaching, is not taking your doubts, thank you very much.

  • For nothing @Davidfilipe. Continue studying on hibernate, is a very important framework in current projects. Mark the answer as correct in case someone comes across a problem similar to yours.

  • Another thing Weslley, if not to abuse your goodwill, I am in a very complicated situation where I am programming alone in a group of 5 people, in the next delivery I need to do some system features, could you tell me where to look? You don’t have to code for me, just tell me where to look would be very helpful.

  • Here are the features http://pastebin.com/rv9NkzS0

  • Send me your email so we can discuss it tonight. I’m off to work now.

  • [email protected]. Send me something and I’ll get in touch, but thank you very much man, good job.

Show 11 more comments

Browser other questions tagged

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