I map business objects to entities and there are cases where the structure of an entity is different from the business objects.
I have userCategories
which are stored in the business object RecipeBo
as strings, because the BO does not have to know anything about the internal structure of the entities. These strings need to be mapped to a relation of Recipe
and RecipeUserCategoryRel
, in addition to it, another field, userId
of RecipeBo
needs to be mapped in this RecipeUserCategoryRel
too.
My approach (which works) is to create a wrapper and manually create the relations by hand, but this looks like tinkering:
public class BoMapper
{
private final static ModelMapper modelMapper = new ModelMapper();
static
{
modelMapper.addMappings(new IngredientMap());
}
public static void map(Object from, Object to)
{
modelMapper.map(from, to);
if (from instanceof RecipeBo && to instanceof Recipe)
{
RecipeBo recipeBo = (RecipeBo)from;
List<String> userCategories = recipeBo.getUserCategories();
List<RecipeUserCategoryRel> recipeUserCategoryRels = new ArrayList<>();
for (String userCategory : userCategories)
{
recipeUserCategoryRels.add(new RecipeUserCategoryRel(userCategory, recipeBo.getUserId()));
}
Recipe recipe = (Recipe)to;
recipe.setRecipeUserCategoryRels(recipeUserCategoryRels);
}
}
}
Is there a better approach of that what I'm doing in BoMapper, e.g. using converters or something? The difficulty is to map each element of the list and add the userId
field too.