【发布时间】:2020-12-17 13:34:40
【问题描述】:
我正在尝试对我的模型类应用验证,但它不起作用,它只是忽略并注册数据库中的值,即使它是 null 或空。
我正在使用龙目岛
我的用户模型:
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@NotNull
@NotBlank
private String nome;
@NotNull
@NotBlank
private BigDecimal incomeMonthly;
@Convert(converter = RiskEnumConverter.class)
private RiskEnum risk;
@OneToOne(cascade = CascadeType.ALL)
private Address address;
我的地址模型:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@NotBlank
private Integer number;
@NotNull
@NotBlank
private String neighborhood;
@NotNull
@NotBlank
private String postalCode;
@NotNull
@NotBlank
private String state;
@NotNull
@NotBlank
private String city;
我的控制器:
@PostMapping
public ResponseEntity<User> save(@Valid @RequestBody User user, HttpServletResponse response) {
User saveUser = this.userService.save(cliente);
publisher.publishEvent(new ResourceCreatedEvent(this, response, saveUser.getId()));
return ResponseEntity.status(HttpStatus.CREATED).body(saveUser);
}
POM 依赖:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
【问题讨论】:
-
也许你需要用@Validated注释你的rest控制器
-
@DanielJacob 一直在数据库中注册并返回 201
-
只添加一个 API 不会做任何事情,你还需要像
hibernate-validator这样的 API 的实现,没有它,什么都不会发生。 -
@M.Deinum 这是通过注解完成的吗?
-
作为@M。 Deinum 强调它,你错过了项目中的依赖项。仅使用
validation-api时,您提供的接口没有实现。