MapStruct
Imagine a big project with a few dozen APIs, and hundreds of Model → DTO conversions... Doing this manually can quickly create much boilerplate code, be prone to error, and consume a lot of time. Luckily for us, there are multiple object mapping frameworks for Java.
Mappers are a “choose your own adventure” situation. The one I recommend is MapStruct. Let's add it to the project
-
We need MapStruct Core, MapStruct Processor, and Lombok Mapstruct Binding dependencies. Add them in the
build.gradle
dependencies section:build.gradleimplementation 'org.mapstruct:mapstruct:1.6.3'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'
annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0' -
Rewrite
UserMapper
so it becomes an interface annotated by MapStruct.src/main/java/dev/pollito/users_manager/adapter/in/rest/mapper/UserMapper.javapackage dev.pollito.users_manager.adapter.in.rest.mapper;
import static org.mapstruct.MappingConstants.ComponentModel.SPRING;
import dev.pollito.users_manager.adapter.in.rest.dto.UserResponseDTO;
import dev.pollito.users_manager.domain.model.User;
import org.mapstruct.Mapper;
@Mapper(componentModel = SPRING)
public interface UserMapper {
UserResponseDTO map(User u);
}
Right-click the main class → Run. Then go to http://localhost:8080/users. Everything should be working as usual.
Remember to commit the progress so far.
git add .
git commit -m "mapstruct"