-
MapStruct 의 @Mapping 사용 방법을 알아보자!Server/Spring Boot 2025. 4. 16. 11:38728x90반응형
🎯 @Mapping 어노테이션 사용 예제
@Mapping
은 DTO와 Entity 간에 필드명이 다를 때나 특정 필드 매핑을 제어하고 싶을 때 사용합니다.예시 1️⃣: 필드명이 다를 경우
// User 엔티티 public class User { private Long id; private String name; }
// UserDto public class UserDto { private Long id; private String username; // 엔티티에서는 'name' }
@Mapper(componentModel = "spring") public interface UserMapper { @Mapping(source = "name", target = "username") UserDto toDto(User user); @Mapping(source = "username", target = "name") User toEntity(UserDto dto); }
설명:
---source
는 원본 객체의 필드,target
은 대상 객체의 필드입니다.예시 2️⃣: 특정 필드 무시하기
매핑하고 싶지 않은 필드는
ignore = true
를 설정합니다.@Mapping(target = "id", ignore = true) User toEntity(UserDto dto);
설명: 예를 들어 새로운 사용자 등록 시
---id
는 DB에서 자동 생성되므로 DTO에서 가져올 필요가 없을 때 사용합니다.예시 3️⃣: 상수 또는 표현식으로 변환하기
@Mapping(target = "status", constant = "ACTIVE") User toEntity(UserDto dto); @Mapping(target = "createdDate", expression = "java(java.time.LocalDate.now())") User toEntityWithDate(UserDto dto);
설명:
constant
: 항상 같은 값으로 설정하고 싶을 때expression
: Java 표현식을 직접 사용하고 싶을 때
예시 4️⃣: 날짜 형식 변환
@Mapping(source = "createdAt", target = "createdDate", dateFormat = "yyyy-MM-dd") UserDto toDto(User user);
설명: 날짜 포맷이 지정되어야 할 때
---dateFormat
속성을 활용합니다.⛳ 그 외 유용한 속성들
속성명 설명 source
원본 객체의 필드명 target
변환 대상 객체의 필드명 ignore
해당 필드 무시 여부 (true/false) constant
고정된 값 지정 expression
자바 표현식 사용 dateFormat
날짜 포맷 지정 728x90반응형'Server > Spring Boot' 카테고리의 다른 글
💡 Java Spring에서 자주 사용하는 ObjectMapper (1) 2025.04.17 MapStruct 의 다양한 사용에 대해 알아보자 (0) 2025.04.16 MapStruct 의 @Mapper 사용에 대해 알아보자! (0) 2025.04.16 [Springboot] 엔티티와 DTO 간 변환시 MapStruct 사용해야 하는 이유? (0) 2025.04.16 [Springboot] 외부 HTTP 호출 Retry와 재처리 전략 (1) 2025.04.15