I am using the Spring Boot framework to create a RESTFUL API and I need a way to avoid the duplication of validation rules when using multiple DTOs as request/response objects for my endpoints.
Using the following example for the Entity
@Entity
public class Post
{
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull @NotBlank @Length(min = 3, max = 21)
private String name;
@Length(max = 128)
private String description;
}
and the DTO
public class CreatePostDTO
{
@NotNull @NotBlank @Length(min = 3, max = 21)
private String name;
@Length(max = 128)
private String description;
}
How can one avoid writing the validation rules for each DTO created? I have considered implementing common interfaces but that would only work well if the entities and DTOs share most if not all fields.