How to fix this and other errors: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'list'?

0

I'm implementing an example of a book on Spring Boot , but after executing, when trying to access the /clientes/list or /clientes/view route in the browser the following errors appear:

  

Failed to convert value of type 'java.lang.String' to required type   'com.greendog.models.Customer'; nested exception is   org.springframework.core.convert.ConversionFailedException: Failed to   convert from type [java.lang.String] to type [java.lang.Long] for   value 'list'; nested exception is java.lang.NumberFormatException: For   input string: "list"

Idonotknowhowtosolve.Herearemycodes:

ClassCliente.java:

packagecom.greendog.modelos;importjava.util.ArrayList;importjava.util.List;importjavax.persistence.Entity;importjavax.persistence.FetchType;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistence.OneToMany;importjavax.validation.constraints.NotNull;importorg.hibernate.annotations.Cascade;importorg.hibernate.annotations.CascadeType;importorg.hibernate.validator.constraints.Length;importcom.greendog.modelos.Pedido;@EntitypublicclassCliente{@Id@GeneratedValue(strategy=GenerationType.AUTO)privateLongid;@NotNull@Length(min=2,max=30,message="O tamanho do nome deve ser entre {min} e {max} caracteres.")
    private String nome;

    @NotNull
    @Length(min=2, max=300, message="O tamanho do endereçomdeve ser entre {min} e {max} caracteres.")
    private String endereco;

    @OneToMany(mappedBy = "cliente", fetch = FetchType.EAGER)
    @Cascade(CascadeType.ALL)
    private List<Pedido> pedidos;


    public Cliente(Long id, String nome, String endereco) {
        this.id = id;
        this.nome = nome;
        this.endereco = endereco;
    }

    public void novoPedido(Pedido pedido) {
        if(this.pedidos == null) pedidos = new ArrayList<Pedido>();
        pedidos.add(pedido);

    }
     /*Getter e Setter */
}

Interface ClienteRepository.java :

package com.greendog.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.greendog.modelos.Cliente;

@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Long>{

}

Class ClienteController.java :

package com.greendog.controladores;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.greendog.modelos.Cliente;
import com.greendog.repositories.ClienteRepository;

@Controller
@RequestMapping("/clientes")
public class ClienteController {

    @Autowired
    private final ClienteRepository clienteRepository = null;

    //Exibe as lista de Clientes
    @GetMapping("/")
    public ModelAndView list() {
        Iterable<Cliente> clientes = this.clienteRepository.findAll();
        return new ModelAndView("clientes/list", "clientes", clientes);
    }

    //Exibe o detalhe de cada cliente
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Cliente cliente) {
        return new ModelAndView("clientes/view", "cliente", cliente);
    }

    //Direciona para criar novo cliente
    @GetMapping("/novo")
    public String createForm(@ModelAttribute Cliente cliente) {
        return "clientes/form";
    }

    //Insere novo cliente através de um formulario
    @PostMapping(params = "form")
    public ModelAndView create(@Valid Cliente cliente, BindingResult result, RedirectAttributes redirect) {
        if(result.hasErrors()){
            return new ModelAndView("clientes/" + "form", "formErros", result.getAllErrors());
        }

        cliente = this.clienteRepository.save(cliente);
        redirect.addFlashAttribute("globalMessage", "Cliente gravado com sucesso!");

        return new ModelAndView("redirect:/" + "clientes/" + "{cliente.id}", "cliente.id", cliente.getId());
    }

    //Atualizar cliente
    @GetMapping(value = "alterar/id")
    public ModelAndView alterarForm(@PathVariable("id") Cliente cliente) {
        return new ModelAndView("cliente/form", "cliente", cliente);
    }

    //Remover Cliente
    public ModelAndView remover(@PathVariable("id") Long id, RedirectAttributes redirect) {
        this.clienteRepository.deleteById(id);
        Iterable<Cliente> clientes = this.clienteRepository.findAll();
        ModelAndView mv = new ModelAndView("clientes/list","clientes", clientes);
        mv.addObject("globalMessage", "Cliente removido com sucesso!");
        return mv;
    }
}

My folder structure for this project:

Completecodeinthe GitHub .

    
asked by anonymous 14.10.2018 / 07:56

1 answer

1

It is falling into this exception because you are incorrectly calling your endpoint, when you call the path / clients / list you are actually passing the string "list" to your view method, which causes your exception, the right would be 15 for instance, 15 being the id of your client, or only clients for calling the list method

editing here the answer because I noticed that you have several errors seeing your git 1. Your methods of your controllers, notice that you are using the ModelAndView method passing in the constructor the name of the view, the name of the model and then the object of the model, your model is called client and at the time of passing you are passing plural customers in some calls, must be the same because otherwise it does not identify. 2 ° your method view you are getting a model but put the id name, I think you got confused here, in my view you should change this Client for long id 3 ° still in your view method, you are passing the client without anything, this la in the front will give an exception by null, changing its method it was like this for me:

@GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") long id) {
        Cliente cliente = new Cliente(id, "Lucas", "123456"); //essa parte aqui você deve trocar pelo seu select
        return new ModelAndView("view", "cliente", cliente);
    }

4 ° in your html you put in the view that is giving error in the line 10 th:if="{globalMessage}" , missing a dollar sign here and therefore was giving error when parsear, the right would be th:if="${globalMessage}"

    
14.10.2018 / 19:37