现有的客户端验证在Spring Boot中?

huangapple go评论69阅读模式
英文:

Existing client validation in Spring boot?

问题

以下是翻译好的内容:

我正在开发一个 Rest API,我需要在注册时验证客户端是否已经存在,使用 CPF 作为键。

这是我的控制器中的 Post 方法:

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

这是我的 Client 类:

@Document
@Data
@AllArgsConstructor
public class Client{
    
    @Id
    private String id;
    
    @NotEmpty(message = "姓名不能为空")
    private String name;
    
    @CPF
    @Size(min = 0, max = 11)
    private String cpf;
}

我不知道如何在我的控制器中执行验证。

提前感谢您。

英文:

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&lt;Client&gt; 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 = &quot;Name cannot be empty&quot;)
    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.

答案1

得分: 0

我不确定这是否是最佳方法,但我第一个猜测是在定义“DTO”时添加 @Column(unique=true),这将在“save”期间引发错误。

另一种更长但可能更透明的方法是定义自己的验证器

更新:
您最初没有提到您正在使用MongoDB。
所以您需要像这样更改Client类:

@Document
@Data
@AllArgsConstructor
public class Client{
与之前相同
....

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

@Indexed(unique=true) 让MongoDB知道此字段必须是唯一的。
就是这样。确保在数据库本身中也有索引。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月17日 23:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63941076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定