0

I am developing a Rest API and I need to validate that the client already exists at the time of registration, using the CPF as the key.

This is my Post method on the controller:

@PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<Client> save(@Valid @RequestBody Client client) {
        return ResponseEntity.ok(this.clientService.save(client));
    }

This is my Client class:

@Document
@Data
@AllArgsConstructor
public class Client{

    @Id
    private String id;

    @NotEmpty(message = "Name cannot be empty")
    private String name;

    @CPF
    @Size(min = 0, max = 11)
    private String cpf;

I have no idea how to perform the validation on my controller.

Thanks in advance.

devnan
  • 33
  • 1
  • 8

1 Answers1

0

I am not sure this is the best way, but my first guess would be to add a @Column(unique=true) where you define DTO, that will throw error during save.

Another longer but probably more transparent way to do it, is defining your own validator.

Upd. You didn't mention initially that you are using MongoDB. So what you need is to change your Client class like so:

@Document
@Data
@AllArgsConstructor
public class Client{
same as before
....

@CPF
@Indexed(unique=true)
@Size(min = 0, max = 11)
private String cpf;

@Indexed(unique=true) Let's MongoDB know that this field must be unique. That's it. Make sure that you have index in the DB itself as well.

Maksym Rudenko
  • 706
  • 5
  • 16
  • Is it possible to be directly in the Post method in the controller? Making a query in the repository using the CPF as key. – devnan Sep 17 '20 at 17:27