0

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;
}
lor lor
  • 121
  • 7
  • use `javax.validation` – Nitin Jan 13 '19 at 11:57
  • I know, you to use it in entities. But need I to annotate DTO or/and fields in DTO? – lor lor Jan 13 '19 at 12:00
  • No need to add annotation on DTO but you need to add annotation on Cline and Skill entity. ref: https://stackoverflow.com/questions/5142065/jsr-303-valid-annotation-nested-object-not-working – Nitin Jan 13 '19 at 12:06

1 Answers1

0

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.

Hong Tang
  • 2,334
  • 1
  • 6
  • 7