如何在Java中为POJO的每个单独字段执行数据类型验证?

xuo3flqw  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(150)

我有一个请求POJO类,它包含所有字符串数据类型字段。当我必须将它们存储到DB时,数据类型必须准确。考虑到我需要验证并将我的每个单独的POJO字段转换为相应的数据类型。此外,请求POJO可能包含200多个字段。我如何验证和转换我的每个字段?这是我的请求POJO看起来像-〉

  1. @Data
  2. public class ProductRequest {
  3. private String goodScore;
  4. private String invalidScore;
  5. private String income;
  6. private String salary;
  7. private String updatedOn;
  8. }

这是我的响应POJO应该看起来像,这些是我实际上需要存储在DB -〉中的类型

  1. @Builder
  2. @Data
  3. public class ProductResponse {
  4. private Integer goodScore;
  5. private Integer invalidScore;
  6. private Float income;
  7. private Double salary;
  8. private LocalDate updatedOn;
  9. }

这就是我如何尝试和实施-〉

  1. public class ProductImplement {
  2. public static void main(String[] args) {
  3. ProductRequest request = new ProductRequest();
  4. try {
  5. ProductResponse.builder()
  6. .goodScore(!StringUtils.hasLength(request.getGoodScore()) ? Integer.parseInt(request.getGoodScore())
  7. : null)
  8. .income(!StringUtils.hasLength(request.getIncome()) ? Float.parseFloat(request.getIncome()) : null)
  9. .invalidScore(
  10. !StringUtils.hasLength(request.getInvalidScore()) ? Integer.parseInt(request.getInvalidScore())
  11. : null)
  12. .salary(!StringUtils.hasLength(request.getSalary()) ? Double.parseDouble(request.getSalary()) : null)
  13. .updatedOn(
  14. !StringUtils.hasLength(request.getUpdatedOn()) ? LocalDate.parse(request.getUpdatedOn()) : null)
  15. .build();
  16. }catch(Exception e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }

因此,如果值不为Null,则解析类型并设置。否则,将字段值设置为Null。但是,在这种情况下,如果在解析时发生任何异常,则整个对象返回Null,对于200个以上的字段执行此操作会非常麻烦。

是否有任何框架来验证单个数据类型,即使在例外情况下,我们也需要忽略该字段并继续解析其他字段?如果我不必使用Respone POJO,也可以。欢迎提出任何建议。

请提出建议。提前感谢!

ssgvzors

ssgvzors1#

您可以使用@NotNull@NotBlank@MinLength@MaxLength
javax.validation应用程序接口
为确保验证,请在***控制器***级别使用@Validated,在***属性***级别使用@Valid

附文参考!

https://www.baeldung.com/spring-valid-vs-validated
Difference between @Valid and @Validated in Spring
这将避免手动验证,并从此删除样板代码:)

相关问题