Indrek Ots Indrek Ots - 2 months ago 15
reST (reStructuredText) Question

Do not validate some fields in the REST layer with JHipster/Spring Boot

When generating a new entity with JHipster, I'm adding fields which are required, but I'm not displaying them in the front-end application's input forms. These are fields which the back-end should fill out. To illustrate, think of a hypothetical blog application. I have a

entity and it has a field
which is annotated with
. The service layer takes care of setting the current date when the entity is being saved.

When the user creates a new post, its fields are validated. Although the user has no option to enter a
, the server responds with a validation error saying that
cannot be null. That's because of the
annotation in the Resource class. At the same time I don't want to remove the
annotation from the entity class since this field is required in the database.

Then I decided to regenerate the same entity but this time I selected the DTO option. Now I can remove the
from the
field in the DTO class. I don't get any validation errors from the REST layer anymore, the DTO is mapped to an entity object and when saving takes place, I'm adding the the current date.

Am I overengineering this problem by introducing a DTO and Mapper classes or is this a reasonable solution?


DTOs are a good approach for your use case, whether you use mappers generated by MapStruct or hand written depend on how complex is your mapping.

Other reasons for using DTOs in JHipster are:

  • hiding some data based on user's role
  • being able to evolve your entities without impacting your REST API
  • formatting some fields
  • aggregating data from several entities into one DTO to avoid too many requests (especially for a mobile client)