[Spring boot] MapStruct

brandon·2025년 6월 7일

spring-boot

목록 보기
11/15

MapStruct is a Java annotation-based code generator that automates the mapping (conversion) between different Java object models — typically between Data Transfer Objects (DTOs) and entity models.

Why use MapStruct?

When building applications, especially layered ones (like Spring Boot apps), you often need to convert between:

Domain entities (used in your database and business logic)

DTOs (used in your REST APIs or service layers)

Writing this conversion code by hand is tedious, repetitive, and error-prone. MapStruct helps by generating this boilerplate code at compile time, so you get fast, type-safe, and efficient mappers.

How does it work?
You define an interface and annotate it with @Mapper. MapStruct then generates an implementation of that interface for you.

Example:
java
복사
편집
@Mapper
public interface CarMapper {

CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);

CarDto carToCarDto(Car car);

}
MapStruct will generate the actual CarMapperImpl class with the mapping logic.

Example of mapping:
java
복사
편집
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
// getters and setters
}

public class CarDto {
private String make;
private int seatCount;
private String type;
// getters and setters
}
You can use MapStruct to map Car to CarDto, even handling cases where field names differ (with additional configuration).

Key Features:
✅ Compile-time generation — no runtime reflection
✅ Very fast and type-safe
✅ Can handle field name differences with @Mapping
✅ Supports nested mappings
✅ Integration with Spring (@Mapper(componentModel = "spring"))
✅ Custom mapping methods if needed

Example with field name differences:
java
복사
편집
@Mapper
public interface CarMapper {

@Mapping(source = "numberOfSeats", target = "seatCount")
CarDto carToCarDto(Car car);

}
Summary:
👉 MapStruct automates the conversion between Java objects (DTO ↔ entity) using compile-time generated code.
👉 It reduces boilerplate and improves maintainability.
👉 It is widely used in modern Java apps, especially with frameworks like Spring.

profile
everything happens for a reason

0개의 댓글