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

[Dúvida] Algorítimo compila, mas a API não devolve os dados do DB

Estou construindo uma API genérica para listar coisas guardadas num banco de dados MySQL, o código compila normalmente mas quando eu tento buscar os dados, o browser me retorna uma Whitelabel page error 404, fiz com base em um tutorial do youtube e eu não consigo encontrar o queeu fiz diferente para a API não devolver os dados. Segue código: Classe Entity:

@Entity
@Table(name = "thing")
public class Thing {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="idthing")
    private Long idThing;
    @Column(name="thingtype")
    private String thingType;
    @Column(name="thing")
    private String thing;
    @Column(name="thingdescription")
    private String thingDescription;


    public Long getIdThing() {
        return idThing;
    }
    public void setIdThing(Long idthing) {
        this.idThing = idthing;
    }
    public String getThingType() {
        return thingType;
    }
    public void setThingType(String thingtype) {
        this.thingType = thingtype;
    }
    public String getThing() {
        return thing;
    }
    public void setThing(String thing) {
        this.thing = thing;
    }
    public String getThingDescription() {
        return thingDescription;
    }
    public void setThingDescription(String thingdescription) {
        this.thingDescription = thingdescription;
    }


}

Classe Entity Controller

@RestController
@RequestMapping("/thing")
public class ThingController {

    private final ThingRepository thingRepository;

    public ThingController(ThingRepository thingRepository) {
        this.thingRepository = thingRepository;
    }
    @GetMapping("/")
    public List<ThingDTO> findAll(){
        var things = thingRepository.findAll();
        return things
                .stream()
                .map(ThingDTO::converter)
                .collect(Collectors.toList());
    }

}

Classe Entity DTO

public class ThingDTO {

    private Long idThing;
    private String thingType;
    private String thing;
    private String thingDescription;

    public static ThingDTO converter(Thing t) {
        var thing = new ThingDTO();
        thing.setIdThing(t.getIdThing());
        thing.setThing(t.getThing());
        thing.setThingDescription(t.getThingDescription());
        thing.setThingType(t.getThingType());
        return thing;
    }

    public Long getIdThing() {
        return idThing;
    }
    public void setIdThing(Long idThing) {
        this.idThing = idThing;
    }
    public String getThingType() {
        return thingType;
    }
    public void setThingType(String thingType) {
        this.thingType = thingType;
    }
    public String getThing() {
        return thing;
    }
    public void setThing(String thing) {
        this.thing = thing;
    }
    public String getThingDescription() {
        return thingDescription;
    }
    public void setThingDescription(String thingDescription) {
        this.thingDescription = thingDescription;
    }


}

A interface Entity Repository

@Repository
public interface ThingRepository extends JpaRepository<Thing,Long> {


}

O video que eu segui foi esse: https://www.youtube.com/watch?v=HR5Np1HmC7c (Apesar do video estar mostrando, eu não instanciei a minha API no docker, o banco de dados é localhost e está configurado no aplication.propperties corretamente)

2 respostas
solução!

Olá, bom dia! Tudo bem? Pelo que pude ver do código, o mais provável que esteja acontecendo é um erro de mapeamento das rotas, o seu controller está com o caminho padrão /thing e o método que busca no banco de dados está com o mapeamento /, o que significa que para chamar o método findAll do controller você precisa usar a URL http://localhost:8080/thing/, se você chamar a mesma URL só que sem a barra no final não vai funcionar e assim você vai receber uma página 404. Uma forma mais recomendada seria fazer o mapeamento do método sem a barra:

@GetMapping
    public List<ThingDTO> findAll(){
        var things = thingRepository.findAll();
        return things
                .stream()
                .map(ThingDTO::converter)
                .collect(Collectors.toList());
    }

Desse jeito as requisições feitas para http://localhost:8080/thing/ ou para http://localhost:8080/thing vão funcionar da mesma forma. Acredito que esse era o problema, já que a questão de usar barra no fim das URLs acaba causando bugs com frequência, mas espero ter ajudado!

Opa! foi só apagar aquela anotation e tudo começou a funcionar, valeu!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software