嵌套对象上的 Javax 验证 - 不工作

问题描述 投票:0回答:3

在我的 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 的存在.

如果我在

@Valid
属性上使用
building
注释,它将验证它的所有字段,但对于这种情况,我只想验证它的
id
.

如何使用 javax 验证来完成?

这是我的控制器:

@PostMapping
public LocationDto createLocation(@Validated({ New.class, LocationGroup.class }) @RequestBody LocationDto location) {
  // save entity here...
}

这是一个正确的请求主体:(不应抛出验证错误)

{
  "name": "Room 44",
  "building": {
    "id": 1
  }
}

这是一个不正确的请求主体:(必须抛出验证错误,因为 building id 丢失

{
  "name": "Room 44",
  "building": { }
}
java spring spring-boot bean-validation
3个回答
70
投票

只需尝试将

@valid
添加到收藏中。它将按照参考hibernate

工作
  @Getter
  @Setter
  @Valid
  @NotNull(groups = { Existing.class })
  private List<LocationDto> locations;

18
投票

@级联类属性必须加注解有效

LocationDTO.class

public class LocationDto {

  @Valid
  private BuildingDto building;
   
  .........

}

8
投票

使用

@ConvertGroup
来自Bean Validation 1.1 (JSR-349).

介绍一个新的验证组说

Pk.class
。将其添加到
groups
BuildingDto

public class BuildingDto {

    @NotNull(groups = {Pk.class, Existing.class, LocationGroup.class})
    // Other constraints
    private Integer id;

    //
}

然后在

LocationDto
级联如下:

@Valid
@ConvertGroup.List( {
    @ConvertGroup(from=New.class, to=Pk.class),
    @ConvertGroup(from=LocationGroup.class, to=Pk.class)
} )
// Other constraints
private BuildingDto building;

延伸阅读:

5.5。来自 Hibernate Validator 参考的组转换

© www.soinside.com 2019 - 2024. All rights reserved.