2
votes

We use Spring MVC, Jackson for json, Hibernate ORM. We need to add front end validations. I came across hibernate validator.

We have a set of Domain classes [DO classes] annotated with JPA. We have another set of POJO classes [DTO classes] annotated for Json binding.

We want to implement infrastructure that does the following:

  1. DTO classes refer to the DO class constraints [where applicable] so that the truth is one place.
  2. Generate json schema , again by reusing the JPA annotations.
  3. Validate input to the rest calls.

For example, instead of the following:

PersonDTO{
  @NotNull
    @Size(min=2, max=60)
    private String firstName;
}

How about:

PersonDTO{
   @MapsTo(com.xyz.domain.PersonDO.firstName.Size) // referring to the JPA annotation
   private String firstName;
}

And then, a custom validator figures out the constraints to uphold by looking at the JPA annotation.

Is the strategy I outlined a typical approach? Any feedback or opinions is appreciated. Can you point me to relevant any articles? Thank you.

1

1 Answers

0
votes

There is no out-of-the-box functionality for copying constraints from one model to another in Hibernate Validator, but you could implement it yourself using existing APIs.

More specifically, there is an API for retrieving constraint metadata (standardized by Bean Validation) and an API for dynamically putting constraints to your types at runtime (provided by Hibernate Validator). You could use the former to read the constraints of your domain model and drive the creation of equivalent constraints on your DTO model using the latter. For that you'd of course need a strategy for matching corresponding types and properties of your source and target model.