API Rest Spring boot

Asked

Viewed 133 times

-2

I’m developing an API to register clients using Rest and Spring, I can already add customers and search by Id, but I would also like to be able to search by name and I’m not getting, would anyone tell me how I can implement this? Thank you very much

Clienterepository:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.api.resources.Cliente;

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

Clienteresource:

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.api.repository.ClienteRepository;
import com.api.resources.Cliente;

@RestController
@RequestMapping(path="/clientes")
public class ClienteResource{
    
    private ClienteRepository clienteRepository;

    public ClienteResource(ClienteRepository clienteRepository){
        super();
        this.clienteRepository = clienteRepository;
    }

    @PostMapping
    public ResponseEntity<Cliente> save(@RequestBody Cliente cliente){
        clienteRepository.save(cliente);
        return new ResponseEntity<>(cliente, HttpStatus.OK);
    }

    @GetMapping
    public ResponseEntity<List<Cliente>> getAll(){
        List<Cliente> clientes = new ArrayList<>();
        clientes = clienteRepository.findAll();
        return new ResponseEntity<>(clientes, HttpStatus.OK);
    }
    
    @GetMapping(path="/{id}")
    public ResponseEntity<Optional<Cliente>> getById(@PathVariable Integer id){
        Optional<Cliente> cliente;
        try{
            cliente = clienteRepository.findById(id);
            return new ResponseEntity<Optional<Cliente>>(cliente, HttpStatus.OK);
        }catch (NoSuchElementException nsee){
            return new ResponseEntity<Optional<Cliente>>(HttpStatus.NOT_FOUND);
        }
    }
    
    @DeleteMapping(path="/{id}")
    public ResponseEntity<Optional<Cliente>> deleteById(@PathVariable Integer id){
    try{
        clienteRepository.deleteById(id);
        return new ResponseEntity<Optional<Cliente>>(HttpStatus.OK);
    }catch (NoSuchElementException nsee){
        return new ResponseEntity<Optional<Cliente>>(HttpStatus.NOT_FOUND);
    }
}

@PutMapping(value="/{id}")
public ResponseEntity<Cliente> update(@PathVariable Integer id, @RequestBody Cliente novoCliente){
    return clienteRepository.findById(id)
            .map(cliente -> {
                cliente.setNome(novoCliente.getNome());
                Cliente clienteUpdated = clienteRepository.save(cliente);
                return ResponseEntity.ok().body(clienteUpdated);
            }).orElse(ResponseEntity.notFound().build());
}
}

Client:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Cliente {


    @GeneratedValue
    @Id
    private int id;
    
    @Column(name = "nome")
    private String nome;
    
    @Column(name = "sexo")
    private String sexo;
    
    @Column (name = "datanascimento")
    private Integer datanascimento;
    
    
    public Cliente(String nome, String sexo, Integer datanascimento) {
        super();
        this.nome = nome;
        this.sexo = sexo;
        this.datanascimento = datanascimento;
    }
    
    public Cliente() {
        
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public Integer getDatanascimento() {
        return datanascimento;
    }

    public void setDatanascimento(Integer datanascimento) {
        this.datanascimento = datanascimento;
    }

    
    
}
  • Just follow the same logic as your search for Id. The point is that it seems to me that you copied a lot of this code structure and you don’t really understand what’s going on there. I suggest you take a look at how the construction of methods works findBy by Spring Data: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-Creation

1 answer

0

Clienterepository.java

@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
    
    List<Cliente> findByNome(String nome);
    
}

Clienteresource.java

@RestController
@RequestMapping(path = "/clientes")
public class ClienteResource {

    @Autowired
    private ClienteRepository clienteRepository;

    // outros métodos e construtores omitidos para ser breve

    @GetMapping
    public ResponseEntity<List<Cliente>> getAll(@RequestParam("nome") String nome) {
        List<Cliente> clientes = new ArrayList<>();
        if(nome == null) {
            clientes = clienteRepository.findAll();
        } else {
            clientes = clienteRepository.findByNome(nome);
        }
        
        return ResponseEntity.ok(clientes);
    }
}

A request for /clientes?nome=Jorge search for all clients named 'Jorge'. If you want to search for parts of the name, change the method of findByNome for findByNomeLike.

Spring Data has a mechanism capable of defining a query derived from the name of a method within a repository, without you having to write JPQL or some Native Query for this (of course this does not cover all use cases).

The method findByNome is understood by the Spring Builder query, then undergoes a parse and generates a query result to be executed in the database. The generated query is something like:

SELECT c FROM Cliente AS c WHERE c.nome = :nome

Browser other questions tagged

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