【问题标题】:Validation a DTO with two entity使用两个实体验证 DTO
【发布时间】:2019-06-07 16:03:41
【问题描述】:

我有一个包含两个实体的 DTO。如何验证这些实体? 我应该使用什么注释? 我使用rest api、JSON、spring boot。 我知道如何验证一个实体。但是我不知道如何处理 DTO。

@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody DTOClient client) {
       ....

        return responseEntity;
    }

public class DTOClient{

//What I should use here to validate these entities?
    private Client client;
    private Skill skill;

}

@Entity
public class Client{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String first_name;

    private String last_name;
}

@Entity
public class Skill{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private int year;
}

【问题讨论】:

  • 使用javax.validation
  • 我知道,你可以在实体中使用它。但是我需要注释 DTO 或/和 DTO 中的字段吗?
  • 无需在 DTO 上添加注释,但您需要在 Cline 和 Skill 实体上添加注释。参考:stackoverflow.com/questions/5142065/…

标签: java validation


【解决方案1】:

javax.validation 用于您要验证的字段。下面的代码是验证client 对象中的first_name 不应为空或空白的示例。

@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody DTOClient client) {
       ....

        return responseEntity;
    }

public class DTOClient{

//What I should use here to validate these entities?
    @Valid
    @NotNull(message="client should not null")
    private Client client;
    private Skill skill;

}

@Entity
public class Client{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank(message="first name of client should not be null or blank")
    private String first_name;

    private String last_name;
}

@Entity
public class Skill{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private int year;
}

简而言之,您需要为 Bean 使用 @Valid,例如控制器方法的参数和非主要字段。以及需要验证的字段的约束注解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2020-09-25
    • 1970-01-01
    • 2011-01-05
    • 2021-06-16
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多