0

Pessoal tenho Rest Api desenvolvida com Spring, hibernate e springboot, estou com com um problema ao fazer uma chamada post pra persistir os dados de um determinado cliente, não gera erro nenhum e também não eh persistido os dados no banco de dados ao testar a chamada no postman ele me retorna o objeto como se estivesse salvo mas o id vem com valor zero, segue meu codigo abaixo

@Entity(name = "TB_CLIENTES")
public class Cliente implements Serializable {

private static final long serialVersionUID = -9073849407172730391L;


@Id   
@Column(name = "CLI_ID", nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)


private Long id;

// A tabela de Cliente se relaciona com Lojista,
// porém através do campo Cliente.CLI_LOJISTA <=> Logista.LOGIN_USER_LOGIN <=>
// LoginUser.LOGIN_USER_LOGIN,
// e não através do ID.
// O relacionamento não é adicionado da maneira correta aqui pois isso degrada a
// performance, bem visível nos logs de SQL do hibernate.

// @NotNull
// @ManyToOne
// @JoinColumn(name = "CLI_LOJISTA", nullable = false, referencedColumnName =
// "LOGIN_USER_LOGIN")
// private Lojista lojista;

@NotNull
@Column(name = "CLI_LOJISTA", nullable = false)
private String lojistaLogin;

@NotNull
@Column(name = "CLI_NOME", nullable = false)
private String nome;

@NotNull
@Column(name = "CLI_ENDERECO", nullable = false)
private String endereco;

@NotNull
@Column(name = "CLI_NUMERO", nullable = false)
private String numero;

@NotNull
@Column(name = "CLI_BAIRRO", nullable = false)
private String bairro;

@NotNull
@Column(name = "CLI_CIDADE", nullable = false)
private String cidade;

@NotNull
@Column(name = "CLI_UF", nullable = false)
private String uf;

@NotNull
@Column(name = "CLI_CEP", nullable = false)
private String cep;

@NotNull
@Column(name = "CLI_FONE1", nullable = false)
private String fone1;

@Column(name = "CLI_FONE2")
private String fone2;

@Column(name = "CLI_OBS")
private String obs;

@Column(name = "CLI_EMAIL")
private String email;

@NotNull
@Column(name = "CLI_RG", nullable = false)
private String rg;

@NotNull
@Column(name = "CLI_CPF", nullable = false)
private String cpf;

@Column(name="CLI_PHOTOCLI", nullable = true)
private String foto;

Interface do controller e sua implementação

@RequestMapping(value = "/new", method = RequestMethod.POST,
    consumes = MediaType.APPLICATION_JSON_VALUE, 
    produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE})
ClientVm newCliente(@RequestBody Cliente edit) 
        throws BadRequestException, NotFoundException ;


@Override
public ClientVm newCliente(@RequestBody Cliente cli)throws BadRequestException, NotFoundException  {
    validator.validateCpf(cli.getCpf());
    try {
        return business.newCliente(cli);
    } catch (IOException ex) {
        Logger.getLogger(ClientServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

camada de negocio e repositorio(utlizada JPARepository)

public ClientVm newCliente(Cliente cli) throws NotFoundException, FileNotFoundException, IOException {
    LoginUser currentUser = clientBusiness.getCurrentUser();
    cli.setLojistaLogin(currentUser.getLoginLojista());
    //cli.setFoto(getPhotoBase64Image(cli.getId()));
     String fileName = null;
    String patch = null;

    if (!cli.getFoto().equals("")){
        byte[] data;
        Date curDate = new Date();

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy-hhmmss");

        fileName = "Logos/photocli/"+cli.getLojistaLogin()+"-"+cli.getCpf()+"-"+format.format(curDate)+".jpg";

        patch = Constants.PHOTO_CLI_PATH +fileName;

        data = Base64.getDecoder().decode(cli.getFoto().getBytes(StandardCharsets.UTF_8));
        try (OutputStream stream = new FileOutputStream(patch)) {
            stream.write(data);
        }
        System.out.println("Salvando base de dados em "+patch);
        cli.setFoto("~/"+fileName);
    }
    Cliente cliRepo = clienteRepository.saveAndFlush(cli);
    clienteRepository.flush();
    ClientVm clienteReturn = new ClientVm(cliRepo);
    //clienteReturn.setFoto(getPhotoBase64Image(cliRepo.getId()));
    return clienteReturn;

}
7
  • Já tentou debugar pra ver se tá caindo no método save? 13/11/2018 às 19:09
  • 1
    ja sim o metodo save é acessado!! 13/11/2018 às 19:23
  • Também cai no return business.newCliente(cli);? 13/11/2018 às 19:34
  • Poste também o log que o Hibernate gera quando você executa o saveAndFlush. 13/11/2018 às 23:01
  • Uma coisa que percebi, quando tento persistir um cliente no hibernate chega os argumentos da seguinte maneira "[2018-11-13 21:21:07,939] DEBUG b.c.p.s.c.aop.logging.LoggingAspect - Enter: br.com.prazoseguro.srv.core.business.ClientBusiness.newCliente() with argument[s] = [Cliente [id=null, lojistaLogin=1295, nome=UBIRATAN TERRA DE MATTOS, endereco=RUA TIRADENTES, numero=415, bairro=CENTRO, cidade=ALTEROSA, uf=MG, cep=37.145-00, fone1=(35) 99752-1886, fone2=(35) 3294-1159, obs=null, [email protected], rg=12435859, cpf=065.700.996-20]] " 13/11/2018 às 23:22

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .