【问题标题】:How to validate Spring-Boot mapped Entitys如何验证 Spring-Boot 映射的实体
【发布时间】:2020-05-07 07:18:38
【问题描述】:

我正在尝试使用 Spring Validator 验证以下方案:

@RestController
@RequestMapping("/bankcode-service")
@Validated
public class BankcodeController {

@Autowired
Delegator delegator;
@Autowired
Delegator delegator;

@Autowired
BankcodeRepository bankcodeRepository;

@DeleteMapping(path = "/bankcode", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public DeferredResult<ResponseEntity<String>> lock(@Valid HttpEntity<BankcodeJSONEntity> httpEntity) {

    DeferredResult<ResponseEntity<String>> response = new DeferredResult<>();
    if (httpEntity.getBody() == null) {
        response.setResult(new ResponseEntity<>("The request was empty!", HttpStatus.BAD_REQUEST));
        return response;
    }
    response.setResult(delegator.delegateUseCase(new LockBankcodeProd(bankcodeRepository, httpEntity.getBody())));
    return response;
}

使用的 DTO 如下所示:

@Data
public class BankcodeJSONEntity {

@NotNull
@Size(min = 8, max = 8)
private String bankcode;
@NotNull
@Size(min = 11, max = 11)
private String bic;
@NotNull
private String ticket;

@Basic
@Temporal(TemporalType.DATE)
@NotNull
private Date date;
@NotNull
private String category;
@NotNull
private String name;

}

但不管我是否通过:

{"bankcode":"00000000", "bic":"AAAAAAAAAAA", "ticket":"SPOC-000000", "date":"2020-01-17", "category":"Fusion", "name":"Fantasiebank"}

或者一个无效的:

{"bankcode":"21750000", "bic":"AAAAAAAA", "ticket":"SPOC-000000", "date":"2020-01-17", "category":"Fusion", "name":"Fantasiebank"}

没有引发约束验证异常。在许多教程中,我看到验证主要是使用具体参数而不是 DTO 完成的。是否可以进行 DTO 验证,因为在 SonarLint 降低我的代码质量之前我只能有 7 个构造函数参数。

我在这里做错了什么?

【问题讨论】:

  • 如果从参数中删除 HttpEntity 会发生什么。并将参数保留为@Valid BankcodeJSONEntity entity。因为 HttpEntity 表示 HTTP 请求或响应,包括 headers 和 body,通常与 RestTemplate 一起使用。
  • 对于控制器,通常作为响应包装器。
  • 您能否将此作为答案发布,以便我接受?谢谢!
  • 很高兴能帮到你。

标签: java spring validation jpa entity


【解决方案1】:

请从参数中删除 HttpEntity。将您的参数更改为@Valid BankcodeJSONEntity entity。 因为 HttpEntity 表示 HTTP 请求或响应,包括 headers 和 body,通常与 RestTemplate 一起使用。而对于控制器,通常作为响应包装器。

public DeferredResult<ResponseEntity<String>> lock(@Valid BankcodeJSONEntityentity) {

【讨论】:

  • 我必须使用 lock(@Valid @RequestBody BankcodeJSONEntityentity) 才能使其工作。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2021-10-16
  • 2021-09-15
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 2016-03-20
  • 2020-08-09
相关资源
最近更新 更多