I am new for MapStruct and trying to learn some functionalities. I am trying to capitalize a title field after mapping from dto to entity. I use the following approach, but ı am not sure if there is already a build function that can be used directly without creating a new method with @AfterMapping
:
@Mapper(componentModel = "spring")
public interface RecipeRequestMapper {
RecipeRequestMapper MAPPER = Mappers.getMapper(RecipeRequestMapper.class);
Recipe toEntity(RecipeRequest dto);
RecipeRequest toDto(Recipe entity);
@AfterMapping
default void getCapitalizedTitle(@MappingTarget Recipe entity, RecipeRequest dto) {
entity.setTitle(WordUtils.capitalizeFully(dto.getTitle()));
}
}
It seems working, but I want to know if there is a proper way for this task?
I think you can use expression like this:
@Mapping(target = "title", expression = java(WordUtils.capitalizeFully(dto.getTitle()))")
Recipe toEntity(RecipeRequest dto);
@Mapping(target = "title", expression = "java(WordUtils.capitalizeFully(entity.getTitle()))")
RecipeRequest toDto(Recipe entity);
Also maybe it is necessary use the full package name:
java(org.apache.commons.text.WordUtils.capitalizeFully(entity.getTitle()))