Indrek Ots
Indrek Ots

Reputation: 3911

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 Post entity and it has a field createdDate which is annotated with @NotNull. 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 createdDate, the server responds with a validation error saying that createdDate cannot be null. That's because of the @Valid annotation in the Resource class. At the same time I don't want to remove the @NotNull 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 @NotNull from the createdDate 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?

Upvotes: 2

Views: 658

Answers (1)

Gaël Marziou
Gaël Marziou

Reputation: 16284

DTOs are a good approach for your use case, whether you use mappers generated by MapStruct or hand written depends 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)

Upvotes: 2

Related Questions