[英]Validation a DTO with two entity
我有兩個實體的DTO。 如何驗證這些實體? 我應該使用什么注釋? 我使用rest api,JSON,spring boot。 我知道如何驗證一個實體。 但是我不知道該如何處理DTO。
@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody DTOClient client) {
....
return responseEntity;
}
public class DTOClient{
//What I should use here to validate these entities?
private Client client;
private Skill skill;
}
@Entity
public class Client{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String first_name;
private String last_name;
}
@Entity
public class Skill{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private int year;
}
將javax.validation
用於要驗證的字段。 下面的代碼是一個示例,用於驗證client
對象中的first_name
不應為null或為空。
@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody DTOClient client) {
....
return responseEntity;
}
public class DTOClient{
//What I should use here to validate these entities?
@Valid
@NotNull(message="client should not null")
private Client client;
private Skill skill;
}
@Entity
public class Client{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotBlank(message="first name of client should not be null or blank")
private String first_name;
private String last_name;
}
@Entity
public class Skill{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private int year;
}
簡而言之,您需要對Bean使用@Valid
,例如控制器方法的參數和非主要字段。 並為需要驗證的字段添加約束注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.