简体   繁体   中英

Validation a DTO with two entity

I have a DTO with two entity. How can I validate these entities? What annotation should I use? I use rest api, JSON, spring boot. I know how to validate one entity. But I don't know what to do with 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;
}

Use javax.validation for the fields which you want to validate. Below code is an example to validate first_name in client object should not null or blank.

@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;
}

In short, you need use @Valid for Bean, like controller methods' params and the fields which not primary. And Constraint annotations for the fields which need validate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM