我有两个实体的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;
}
答案 0 :(得分:0)
对要验证的字段使用javax.validation
。下面的代码是一个示例,用于验证first_name
对象中的client
不应为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
,例如控制器方法的参数和非主要字段。并为需要验证的字段添加约束注释。