0
0
Spring Bootframework~30 mins

MapStruct for automatic mapping in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
MapStruct for automatic mapping in Spring Boot
📖 Scenario: You are building a Spring Boot application that manages user data. You want to convert between UserEntity objects from the database and UserDTO objects used in your API responses. Doing this manually is repetitive and error-prone.MapStruct is a tool that automatically generates code to map between these two types, saving time and avoiding mistakes.
🎯 Goal: Build a simple MapStruct mapper interface that converts between UserEntity and UserDTO classes automatically.
📋 What You'll Learn
Create a UserEntity class with fields id, name, and email.
Create a UserDTO class with the same fields.
Create a MapStruct mapper interface called UserMapper.
Add a method to map from UserEntity to UserDTO.
Add a method to map from UserDTO to UserEntity.
💡 Why This Matters
🌍 Real World
In real applications, converting between database entities and API data transfer objects is common. MapStruct automates this conversion, saving time and reducing errors.
💼 Career
Knowing how to use MapStruct is valuable for Java developers working with Spring Boot, as it improves code quality and productivity in backend development.
Progress0 / 4 steps
1
Create UserEntity class
Create a Java class called UserEntity with private fields Long id, String name, and String email. Include public getters and setters for each field.
Spring Boot
Need a hint?

Define a public class named UserEntity. Add private fields for id, name, and email. Then add public getter and setter methods for each field.

2
Create UserDTO class
Create a Java class called UserDTO with private fields Long id, String name, and String email. Include public getters and setters for each field.
Spring Boot
Need a hint?

Define a public class named UserDTO. Add private fields for id, name, and email. Then add public getter and setter methods for each field.

3
Create UserMapper interface with MapStruct
Create a MapStruct mapper interface called UserMapper. Annotate it with @Mapper. Add a method UserDTO toDto(UserEntity userEntity) to map from UserEntity to UserDTO. Add a method UserEntity toEntity(UserDTO userDTO) to map from UserDTO to UserEntity.
Spring Boot
Need a hint?

Define an interface named UserMapper. Add the @Mapper annotation above it. Inside, add two methods: one to convert UserEntity to UserDTO, and another to convert UserDTO to UserEntity.

4
Complete MapStruct setup with componentModel
Modify the @Mapper annotation on UserMapper to include componentModel = "spring". This allows Spring Boot to detect and inject the mapper automatically.
Spring Boot
Need a hint?

Update the @Mapper annotation to @Mapper(componentModel = "spring"). This tells MapStruct to generate a Spring bean for the mapper.