0

I have entities that represent my database - User, Recipe and Tag. For data manipulation I use DTO. So UserDTO, RecipeDTO, TagDTO. When I define a relationship between entities, I use its basic User, Recipe, Tag form, but when I define these relationships in a DTO class, I use its DTO form.

For example:

DTO Class looks like this

public class UserDTO{
 private String name;
 private String email
 private List<RecipeDTO>
}

public class RecipeDTO{
 private String title;
 private String description;
 private UserDTO user;
}

I know how to map a DTO to an entity so that I can perform operations (CRUD) on the data in the database.

private Recipe convertToEntity(RecipeDTO recipeDTO){
 Recipe recipe = new Recipe();
 recipe.setTitle(recipeDTO.getTitle);
 recipe.setDescription(recipeDTO.getDescription);
}

But the RecipeDTO also has a UserDTO in it, which I also need to map to an entity. How do I do this? So I am trying to achieve a mapping inside the mapping .... (??)

I can think of the following solution.

Create method that converts UserDTO to User:

private User convertUser(UserDTO userDTO){
 User user = new User();
 user.setName(userDTO.getName());
 user.setEmail(userDTO.getEmail());
}

And then use it while mapping RecipeDTO to Recipe.

private Recipe convertToEntity(RecipeDTO recipeDTO){
 Recipe recipe = new Recipe();
 recipe.setTitle(recipeDTO.getTitle());
 recipe.setDescription(recipeDTO.getDescription());
 //Convert UserDTO
 recipe.setUser(convertUser(recipeDTO.getUser()));
}

I'm not sure if this is the right solution, as there will be more and more mappings as the code gets bigger.

m_novak
  • 117
  • 10

1 Answers1

1

The approach you described is not wrong and will work, but doing it that way will indeed involve a lot of hard work.

The way this is usually done in the industry is by letting a library do that work for you.

The two most popular mapping libraries for java are:

https://mapstruct.org/ (which uses annotation processing at compile time and auto-generates basically the same mapping code as in your example)

and

http://modelmapper.org/ (which uses black magic and reflection)

They are both easy to setup/learn and either will do the job (including mapping nested objects as in your example), so take a look at the “getting started“ section and pick the one you find more intuitive to use.

My personal recommendation would be to pick Mapstruct, as it has way fewer gotchas, generates clean human-readable code and avoids using reflection.

Bragolgirith
  • 2,167
  • 2
  • 24
  • 44