【问题标题】:Javax validation on nested objects - not working嵌套对象的 Javax 验证 - 不起作用
【发布时间】: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 中验证属性 namebuilding 不为空,但 我无法验证建筑物内是否存在属性 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


【解决方案1】:

只需尝试将@valid 添加到收藏夹。它将按照参考 hibernate

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

【讨论】:

  • 这是简单而准确的解决方案!
【解决方案2】:

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

引入一个新的验证组,比如Pk.class。将其添加到groupsBuildingDto

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. Group conversion 来自 Hibernate Validator 参考。

【讨论】:

    【解决方案3】:

    @Valid 注解必须添加到级联类属性中。

    LocationDTO.class

    public class LocationDto {
    
      @Valid
      private BuildingDto building;
       
      .........
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2011-06-28
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2014-01-16
      • 1970-01-01
      相关资源
      最近更新 更多