【问题标题】:Spring @NotNull validation constraint for a list of objects is not showing the required element name对象列表的 Spring @NotNull 验证约束未显示所需的元素名称
【发布时间】:2019-09-24 23:25:03
【问题描述】:

我在我的 DTO 中使用 @NotNull 注释来验证某些字段不能为空。

就像这样:

@NotEmpty
private String exampleField;

And I am getting the next error message:

{
"error": {
    "errorCode": "400",
    "message": "[must not be empty]",
    "id": "249ac058-dde9-497f-8a33-66730a4acb6a",
    "time": 1569366486479
},
"status": 400
}

问题是我没有在错误响应中获取元素名称。我认为这是因为在这个请求中我有我的 DTO 列表。就像这样:

List<ChildDTO> child)

因为在另一个服务中只有一个对象的 requestBody 就这样:

ChildDTO child

我有回应:

{
    "errorCode": "400",
    "message": "{exampleField=[must not be empty]}",
    "id": "4f6add3d-ed47-4b4c-b5a7-90c740407aae",
    "time": 1569366693073
}

我认为,当我发送对象列表并且其中一个字段具有此验证时,正在发生某些事情并且元素名称在最终消息中丢失。

这是使用 DTO 的方法:

@PostMapping(CHILD_PATH)
@Validated(OnCreationRequest.class)
@ResponseStatus(HttpStatus.CREATED)
public ChildDTO register(@RequestBody @Valid ChildDTO CHILD) {
    return CHILDService.saveCHILD(CHILD);
}

@PostMapping(CHILD_REGISTER_PATH_LIST)
@Validated(OnCreationRequest.class)
@ResponseStatus(HttpStatus.CREATED)
public boolean registerAll(@RequestBody @Valid List<ChildDTO> CHILDs) {
    return CHILDService.saveAllCHILDs(CHILDs);
}

问题出在第二个,因为我有一个列表:

List<ChildDTO> CHILDs

有什么想法吗?

【问题讨论】:

  • 您可能需要显示更多代码,并且您是否在注释@NotNull(message="Account id can not be null") 中指定消息?
  • @Deadpool 我已经更新了代码,你之前所说的工作但消息不完整。我的意思是我只看到“帐户 ID 不能是”消息。

标签: java validation constraints notnull


【解决方案1】:

创建另一个类为Children,并将List&lt;ChildDTO&gt; 声明为@NotNull

class Children {

    @NotNull
    private List<ChildDTO> children;

    /**
     * getters & setters
     */
}

使用Children 类更新您的控制器功能。

@PostMapping(CHILD_REGISTER_PATH_LIST)
@Validated(OnCreationRequest.class)
@ResponseStatus(HttpStatus.CREATED)
public boolean registerAll(@RequestBody @Valid Children children) {
    return CHILDService.saveAllCHILDs(children);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2019-01-07
    • 2012-11-13
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多