Null return for List<String> method

Asked

Viewed 790 times

-1

I have a method with return type List<String>, when a query is made I can return a value or nothing:

public class Repositorio {

     @PersistenceContext
      private EntityManager em;

      public List<String> listaEscritorio(Integer id){
        if(id>0) {

            Query query = em.createQuery("select * from escritorio where id="+id);
            return query.getResultList();
        }
         return null;
      }
}

However, the Java IDE returns an error to the return type null.

Controller Code

@RequestMapping(path ="/select2")
    public @ResponseBody List<String> Escritorios(){

        List<String> resultado = repo.listaEscritorio(3);

        return resultado;
    }

I want to return the name of an office. I am sweating a repository class to perform query operations in the database.

Entity Office

@Entity
@Table(name="escritorio")
public class Escritorio {
    @Id 
    private Long id;
    private String cnpj;
    private Long contato;
    private Long endereco;
    private String nome;
    private Long qtd_maximo_atividade;
    private Long qtd_maximo_prazo_juridico;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCnpj() {
        return cnpj;
    }
    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }
    public Long getContato() {
        return contato;
    }
    public void setContato(Long contato) {
        this.contato = contato;
    }
    public Long getEndereco() {
        return endereco;
    }
    public void setEndereco(Long endereco) {
        this.endereco = endereco;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public Long getQtd_maximo_atividade() {
        return qtd_maximo_atividade;
    }
    public void setQtd_maximo_atividade(Long qtd_maximo_atividade) {
        this.qtd_maximo_atividade = qtd_maximo_atividade;
    }
    public Long getQtd_maximo_prazo_juridico() {
        return qtd_maximo_prazo_juridico;
    }
    public void setQtd_maximo_prazo_juridico(Long qtd_maximo_prazo_juridico) {
        this.qtd_maximo_prazo_juridico = qtd_maximo_prazo_juridico;
    }

}

Systen.proprierty

database_url=jdbc:postgresql://localhost:5432/nome_banco
database_username=postgres
database_password=postgres

Error: inserir a descrição da imagem aqui

Error message in Postman

{ "timestamp": "2018-08-02T21:19:46.019+0000", "status": 500, "error": "Internal Server Error", "message": "No message available", "path": "/monitor/office" }

Eclipse error

Servlet.service() for Servlet [dispatcherServlet] in context with path [] threw Exception [Request Processing failed; nested Exception is java.lang.Nullpointerexception] with root cause

Error message:

2018-08-02 18:20:35.905 ERROR 7368 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at controller.ControllerGeral.escritorios(ControllerGeral.java:70) ~[bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_161]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_161]
  • Look, you can even have a Warning of [unchecked]. Nor would I doubt to see this as the cause of ClassCastException or NullPointerException. But build error I think not. If it gives some error, post the error message in the question.

  • 1

    This query of yours is all wrong: 1. why concatenate the id and not use parameter? It is practical to avoid sql Injection; 2. Which JPA preview are you using? It is probably not necessary to check if it is greater than 0 and otherwise return null, Query#getResultList(), the most commonly used providers will return an empty list if it has not worked, or return Optional; 3. avoid returning null references, only serve to cause Npes; 4. prefer TypedQuery; 5. entidade is a JPA entity? ; 6. what is the error the IDE is pointing to?

  • I want to return the name of an office. I am sweating a Repository class to perform query operations in the bank.

  • Can a single office have multiple names? How did you map this entity Escritorio?

  • Are you using Maven? Puts the settings in pom.xml

  • I’m using gradlew

  • You added the javax dependency.Servlet-api in version 3.1 because you are using Tomcat 8.5?

  • This problem is much like yours: https://stackoverflow.com/questions/39129725/null-pointer-exception-in-dispatcher-servlet

Show 3 more comments

2 answers

3

Since you want to return the name of the offices, assuming you are using JPA 2.2, do this:

public class Repositorio {

    @PersistenceContext
    private EntityManager em;

    public List<String> listaEscritorio(int id) {
        return em.createQuery("select * from escritorio where id = ?", Escritorio.class)
                .setParameter("id", id)
                .getResultStream()
                .map(Escritorio::getNome)
                .collect(Collectors.toList());
    }
}
@RequestMapping(path ="/select2")
public @ResponseBody List<String> escritorios() {
    return repo.listaEscritorio(3);
}

Some remarks:

  • The parameter of listaEscritorio was Integer instead of int. In its original code, pass a null it would give NullPointerException and it would be a meaningless operation.

  • Don’t come back null in methods that return lists. This is asking to have a NullPointerException after. You can return an empty list.

  • How do you think a select * could bring only strings as results when the table in question has at least two fields? What you have to do is do an entity search and then you take the name of that entity’s office.

  • This supposes that you have an entity Escritorio properly mapped and that there is a method getNome() that returns a String.

EDITED

However, as an office can only have a single name and you are searching for id, soon you will only return a single name in the list. So, it is not even meaningful to use list for this:

public class Repositorio {

    @PersistenceContext
    private EntityManager em;

    public String nomeEscritorio(int id) {
        Escritorio x = em.find(Escritorio.class, id);
        return x == null ? "" : x.getNome();
    }
}
@RequestMapping(path ="/select2")
public @ResponseBody String escritorios() {
    return repo.nomeEscritorio(3);
}
  • In what scenario Integer the parameter and pass null would give NPE and meaningless? setParameter accepts null references without problem, maybe only would not return anything if id is not null. It even makes sense to be the wrapper, to avoid unnecessary Boxing/Unboxing

  • @Brunswick Look at his original source code: if(id>0) - That would make Unboxing and give an NPE.

1

I think you have to "tipar" the return of createQuery. I think something like that:

TypedQuery<String> query = em.createQuery("select * from escritorio where id="+id, String.class);

Must be giving casting error.

Because the createQuery must be returning a List<Object> or simply a List, and the signature of your method requires a List<String>.

And also this your code is strange. Office is a persistence class right? Then you would have to return a list of Offices, not a list of String.

And if you want to look for the primary key, you have to use the EntityManager#find();

Escritorio e = em.find(Escritorio.class, id);
  • In which version of JPA EntityManager#createQuery(String, Class) returns Query? Is returned TypedQuery, nay Query. createQuery does not return List of no type, who returns this are result lists.

  • I want to return the name of an office. I am sweating a Repository class to perform query operations in the bank.

  • @Brunocésar on Query, I just copied what he did because in his code, I didn’t check. Really EntityManager#createQuery(String, Class) will return a TypedQuery<Class>, but that other mistake there was to simplify, what really matters to him, at the level that he is, is the final result.

Browser other questions tagged

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