-
[Springboot] 엔티티와 DTO 간 변환시 MapStruct 사용해야 하는 이유?Server/Spring Boot 2025. 4. 16. 11:29728x90반응형
✅ MapStruct 기본 설정 방법
1. 의존성 추가 (Maven 기준)
<dependencies> <!-- MapStruct Core --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> </dependency> <!-- MapStruct Processor --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
Gradle을 사용하는 경우:
dependencies { implementation 'org.mapstruct:mapstruct:1.5.5.Final' annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final' }
2. Mapper 인터페이스 작성 예시
@Mapper(componentModel = "spring") public interface UserMapper { UserDto toDto(User user); User toEntity(UserDto userDto); }
💡 TIP:
componentModel = "spring"
옵션을 사용하면 해당 Mapper를 Spring Bean으로 등록할 수 있어@Autowired
로 주입받을 수 있어요.
✅ MapStruct vs ModelMapper
항목 MapStruct ModelMapper 동작 방식 컴파일 타임에 코드 생성 런타임에 Reflection 사용 성능 매우 빠름 (정적 바인딩) 느림 (동적 바인딩 + 리플렉션) 타입 안정성 컴파일 시 타입 체크 가능 런타임 오류 가능 유지보수 명시적인 코드로 명확함 자동 매핑이 편리하나 가독성 낮을 수 있음 커스터마이징 @Mapping
,@Named
, default methods로 정밀하게 제어 가능Expression 설정은 가능하지만 복잡한 매핑은 힘듦 러닝커브 초기 세팅 약간 필요하지만 구조적 설정은 간단하지만 복잡한 매핑 제약
✨ MapStruct를 추천하는 이유
- 대규모 프로젝트에서 성능 이슈를 줄일 수 있음
- DTO ↔ Entity 간 매핑이 명시적이라 유지보수와 디버깅이 쉬움
- 컴파일 타임 에러 검출로 안전한 개발 가능
- Spring과의 궁합도 매우 좋음 (
@Mapper(componentModel = "spring")
)
728x90반응형'Server > Spring Boot' 카테고리의 다른 글
MapStruct 의 @Mapping 사용 방법을 알아보자! (1) 2025.04.16 MapStruct 의 @Mapper 사용에 대해 알아보자! (0) 2025.04.16 [Springboot] 외부 HTTP 호출 Retry와 재처리 전략 (1) 2025.04.15 Springboot Timezone(타임존) 에 대해 알아보자! (1) 2025.04.15 [Springboot] 스프링부트 개요 (0) 2023.01.18