我正在尝试在Spring Boot中验证请求正文。 当发布控制器使用下面的JSON在DB中创建记录时。很好。
{
"test1": "string",
"test2": "string",
"test3": "string", <--this has @Null in the entity
"test4": "string"
}
但是,当实体中的键之一为@NULL时,它将仍然能够在数据库中创建记录。我想知道是否有什么可以验证密钥并返回错误。
{
"test1": "string",
"test2": "string",
"test5": "string", <- wrong key by mistake
"test4": "string"
}
实体类
@Entity
@Table(name = "test")
@Data
@NoArgsConstructor
public class Test implements Serializable {
@Id
@Column(name = "test1")
private String test1;
@Column(name = "test2")
@NotNull
private String test2;
@Column(name = "test3")
private String test3;
@Column(name = "test4")
private String test4;
}
答案 0 :(得分:0)
答案 1 :(得分:0)
If u want to Validate request body in JSON u can use @Valid
@PostMapping("/books")
Book newBook(@Valid @RequestBody Test test) {
return repository.save(Test);
}
@Column(name = "test3")
@NotNull(message = "Please provide a test3")
private String test3;
if u want on key order
JsonPropertyOrder({ "test1", "test2", "test3", "test4" })
public class Test implements Serializable {
}