Dan*_*llo 17 java spring bean-validation spring-boot
在我的 Spring Boot 项目中,我有两个 DTO 正在尝试验证,LocationDto 和 BuildingDto。LocationDto 有一个 BuildingDto 类型的嵌套对象。
这些是我的 DTO:
位置Dto
public class LocationDto {
@NotNull(groups = { Existing.class })
@Null(groups = { New.class })
@Getter
@Setter
private Integer id;
@NotNull(groups = { New.class, Existing.class })
@Getter
@Setter
private String name;
@NotNull(groups = { New.class, Existing.class, LocationGroup.class })
@Getter
@Setter
private BuildingDto building;
@NotNull(groups = { Existing.class })
@Getter
@Setter
private Integer lockVersion;
}
Run Code Online (Sandbox Code Playgroud)
建筑Dto
public class BuildingDto {
@NotNull(groups = { Existing.class, LocationGroup.class })
@Null(groups = { New.class })
@Getter
@Setter
private Integer id;
@NotNull(groups = { New.class, Existing.class })
@Getter
@Setter
private String name;
@NotNull(groups = { Existing.class })
@Getter
@Setter
private List<LocationDto> locations;
@NotNull(groups = { Existing.class })
@Getter
@Setter
private Integer lockVersion;
}
Run Code Online (Sandbox Code Playgroud)
目前,我可以验证我LocationDto的属性name并且building不为空,但我无法验证 building 内的属性 id 的存在。
如果我@Valid在building属性上使用注释,它将验证其所有字段,但对于这种情况,我只想验证其id.
如何使用 javax 验证来完成?
这是我的控制器:
@PostMapping
public LocationDto createLocation(@Validated({ New.class, LocationGroup.class }) @RequestBody LocationDto location) {
// save entity here...
}
Run Code Online (Sandbox Code Playgroud)
这是一个正确的请求正文:(不应抛出验证错误)
{
"name": "Room 44",
"building": {
"id": 1
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个不正确的请求正文:(必须抛出验证错误,因为缺少建筑物 ID)
{
"name": "Room 44",
"building": { }
}
Run Code Online (Sandbox Code Playgroud)
luc*_*cid 50
只需尝试添加@valid到集合中。它将按照参考hibernate 工作
@Getter
@Setter
@Valid
@NotNull(groups = { Existing.class })
private List<LocationDto> locations;
Run Code Online (Sandbox Code Playgroud)
小智 25
级联类属性必须添加@Valid注解。
位置DTO.class
public class LocationDto {
@Valid
private BuildingDto building;
.........
}
Run Code Online (Sandbox Code Playgroud)
使用@ConvertGroup来自Bean验证1.1(JSR-349) 。
引入一个新的验证组 say Pk.class。将它添加到groups的BuildingDto:
public class BuildingDto {
@NotNull(groups = {Pk.class, Existing.class, LocationGroup.class})
// Other constraints
private Integer id;
//
}
Run Code Online (Sandbox Code Playgroud)
然后LocationDto级联如下:
@Valid
@ConvertGroup.List( {
@ConvertGroup(from=New.class, to=Pk.class),
@ConvertGroup(from=LocationGroup.class, to=Pk.class)
} )
// Other constraints
private BuildingDto building;
Run Code Online (Sandbox Code Playgroud)
进一步阅读:
5.5. 来自 Hibernate Validator 参考的组转换。
| 归档时间: |
|
| 查看次数: |
16346 次 |
| 最近记录: |