Member-only story
Mastering Object Mapping in Spring Boot with @Mapper and @Mapping
In Spring Boot, if you’re working with data transfer objects (DTOs) or entity mapping between layers (e.g., between service and persistence layers), using a mapping framework like MapStruct can be helpful. The @Mapper
and @Mapping
annotations are part of MapStruct, a code generator that simplifies the process of mapping between Java objects.
Key Concepts of MapStruct:
- @Mapper:
This annotation is applied to an interface or abstract class. It indicates that this interface is a Mapper, and the MapStruct processor will automatically generate an implementation for it.
@Mapper
public interface UserMapper {
UserDTO toDto(User entity);
User toEntity(UserDTO dto);
}
In this example, UserMapper
is a mapper interface that will map a User
entity to UserDTO
and vice versa.
@Mapping:
This annotation is used inside a Mapper interface when you want to explicitly define how fields in one object map to fields in another. It is used when the fields don’t have a direct match or if additional logic is required.
@Mapper
public interface UserMapper {
@Mapping(source = "name", target = "fullName")
@Mapping(source = "address.street", target = "streetName")
UserDTO toDto(User entity);
@Mapping(source = "fullName", target = "name")
@Mapping(source = "streetName", target = "address.street")
User…