pull请求不更新存储库

ht4b089n  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(246)

我正试图通过发送带有以下代码的以下请求来更改perfilrepository中的perfil对象:

package br.com.bandtec.projetocaputeam.controller;

import br.com.bandtec.projetocaputeam.dominio.*;
import br.com.bandtec.projetocaputeam.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/caputeam")
public class CaputeamController {

//USER CLASS

    public abstract class Perfil {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "nome")
    @NotNull
    @Size(min = 5,max = 30)
    @Pattern(regexp = "^[a-zA-Z\s]*$", message = "Nome inválido! Digite apenas letras e espaçamento") //Permite apenas letras e espaço
    private String nome;

    @NotNull
    @CPF
    private String cpf;

    @Column(name = "email")
    @NotNull
    @Email
    private String email;

    @NotNull
    @Size(min = 5,max = 12)
    private String senha;

    private Integer telefone;

    @DecimalMin("0")
    @DecimalMax("5")
    private Double avaliacao;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id_endereco")
    private Endereco endereco;

    @NotNull
    private String tipoPerfil;

    @OneToOne(cascade = CascadeType.ALL)
    private Categoria categoriaAutonomo;

    //Getters
    public Integer getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public String getCpf() {
        return cpf;
    }

    public String getEmail() {
        return email;
    }

    public String getSenha() {
        return senha;
    }

    public Integer getTelefone() {
        return telefone;
    }

    public Double getAvaliacao() {
        return avaliacao;
    }

    public Endereco getEndereco() {
        return endereco;
    }

    public String getTipoPerfil() {
        return tipoPerfil;
    }

    public Categoria getCategoriaAutonomo() {
        return categoriaAutonomo;
    }

    //Setters
    public void setTipoPerfil(String tipoPerfil) {
        this.tipoPerfil = tipoPerfil;
    }

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

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public void setTelefone(Integer telefone) {
        this.telefone = telefone;
    }

    public void setAvaliacao(Double avaliacao) {
        this.avaliacao = avaliacao;
    }

    public void setEndereco(Endereco endereco) {
        this.endereco = endereco;
    }

    public void setCategoriaAutonomo(Categoria categoriaAutonomo) {
        this.categoriaAutonomo = categoriaAutonomo;
    }
}

//---存储库

@Autowired
    private PerfilService perfilService = new PerfilService();
//--- USUARIOS
    @GetMapping("/usuarios")
    public ResponseEntity getUsuario(){
        return perfilService.getPerfisRepository();
    }

    @PostMapping("/cadastrar-usuario")
    public ResponseEntity cadastrarUsuario(@RequestBody @Valid Perfil novoPerfil){
        return perfilService.cadastrarUsuario(novoPerfil);
    }

    @PutMapping("/usuarios/{id}")
    public ResponseEntity alterarUsuario(@RequestBody @Valid Perfil usuarioAlterado, @PathVariable int id){
        return perfilService.alterarPerfil(usuarioAlterado,id);
    }

这就是我改变perfil对象的方法

public ResponseEntity alterarPerfil(Perfil perfilAlterado, int id){

    perfisRepository.findById(id).map(perfil -> {
        perfil.setNome(perfilAlterado.getNome());
        perfil.setEmail(perfilAlterado.getEmail());
        perfil.setTelefone(perfilAlterado.getTelefone());
        return ResponseEntity.ok().build();
});
return ResponseEntity.badRequest().body("Alteração inválida!");

}
我把我的put请求发送给 Postman 如下:

{
    "id": 1,
    "nome": "Beatriz Barros",
    "cpf": "103.725.810-05",
    "email": "bia@hotmail.com",
    "senha": "121520",
    "telefone": 1134577777,
    "avaliacao": 4.9,
    "endereco": {
        "id": 1,
        "cep": "03311111",
        "bairro": "Vila Poeira",
        "logradouro": "RuaFlor",
        "numeroLogradouro": 7,
        "complemento": null,
        "uf": "sp",
        "cidade": "SaoPaulo"
    },
    "tipoPerfil": "autonomo",
    "categoriaAutonomo": {
        "id": 1,
        "nome": "Jardineiro",
        "descricao": null
    },
    "precoAutonomo": 0.0
}

但它总是返回状态400错误请求!我已经试着只发送我想更改的字段(姓名、电子邮件和电话),但也没有成功
我也试着发送有和没有身份证,没有任何工作
如何发送正确的请求?

d6kp6zgx

d6kp6zgx1#

其实你就是这么做的。

perfisRepository.findById(id).map(perfil -> {
        perfil.setNome(perfilAlterado.getNome());
        perfil.setEmail(perfilAlterado.getEmail());
        perfil.setTelefone(perfilAlterado.getTelefone());
        return ResponseEntity.ok().build();
});
``` `perfil -> { /* */ }` 实际上是一个lambda表达式,或者换句话说:一个匿名方法。所以不是回到家里 `alterarPerfil` 方法,则返回匿名方法。
我从来没有和spring一起工作过,但是通过阅读文档,我认为 `perfisRepository` 正在实施 `CrudRepository` 接口。
正确的代码应该是:

Perfil oldObject = perfisRepository.findById(id).get();

if(oldObject == null) return ResponseEntity.badRequest().body("Alteração inválida!");

oldObject.setNome(perfilAlterado.getNome());
oldObject.setEmail(perfilAlterado.getEmail());
/* and so on - you probably want to use reflection or a helping class to save you some time here */
// For a given entity, save will act as update too.
perfisRepository.save(oldObject);
return ResponseEntity.ok().build();

因为在您的代码中,您没有保留任何更改。

相关问题