ネストされたオブジェクト上のjavaxの検証 - 機能していません

ダニエル・カスティージョ:

私の春ブーツプロジェクトで、私は私が検証、LocationDtoとBuildingDtoにしようとしている2 DTOのを持っています。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、その性質namebuildingnullではありませんが、私は内部の建物であるプロパティ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
  }
}

これは間違ったリクエストボディである:(ので、検証エラーをスローする必要があり、建物のIDが欠落しています

{
  "name": "Room 44",
  "building": { }
}
ミナールマフムード:

使用@ConvertGroupからビーン検証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バリデータの参照から。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=186090&siteId=1