英文:
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<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.
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论