【发布时间】:2019-01-01 21:51:34
【问题描述】:
在我的 Spring Boot 项目中,我有两个要验证的 DTO,LocationDto 和 BuildingDto。 LocationDto 有一个 BuildingDto 类型的嵌套对象。
这些是我的 DTO:
LocationDto
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;
}
BuildingDto
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;
}
目前,我可以在 LocationDto 中验证属性 name 和 building 不为空,但 我无法验证建筑物内是否存在属性 ID .
如果我在building 属性上使用@Valid 注释,它将验证其所有字段,但对于这种情况,我只想验证其id。
如何使用 javax 验证来做到这一点?
这是我的控制器:
@PostMapping
public LocationDto createLocation(@Validated({ New.class, LocationGroup.class }) @RequestBody LocationDto location) {
// save entity here...
}
这是一个正确的请求正文:(不应引发验证错误)
{
"name": "Room 44",
"building": {
"id": 1
}
}
这是一个不正确的请求正文:(必须抛出验证错误,因为缺少建筑物 ID)
{
"name": "Room 44",
"building": { }
}
【问题讨论】:
-
什么是“ExistingClass”?
标签: java spring spring-boot bean-validation