In my Spring Boot project I have two DTO's which I'm trying to validate, LocationDto and BuildingDto. The LocationDto has a nested object of type BuildingDto.
These are my DTO's:
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;
}
Currently, I can validate in my LocationDto
that the properties name
and building
are not null, but I can't validate the presence of the property id which is inside building.
If I use the @Valid
annotation on the building
property, it would validate all of its fields, but for this case I only want to validate its id
.
How could that be done using javax validation?
This is my controller:
@PostMapping
public LocationDto createLocation(@Validated({ New.class, LocationGroup.class }) @RequestBody LocationDto location) {
// save entity here...
}
This is a correct request body: (should not throw validation errors)
{
"name": "Room 44",
"building": {
"id": 1
}
}
This is an incorrect request body: (must throw validation errors because the building id is missing)
{
"name": "Room 44",
"building": { }
}