Server/Spring Boot
MapStruct 의 @Mapping 사용 방법을 알아보자!
hoonylab
2025. 4. 16. 11:38
728x90
반응형
🎯 @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
반응형