Table of Content
MapStruct 사용하기 고급
DTO – Entity 준비
@Setter
@Getter
@NoArgsConstructor
@Entity
public class TestBrands {
private String brandId;
private String partnerId;
private String brandName;
private String useyn = "Y";
private String partnerId2;
}
@Getter
@Setter
@NoArgsConstructor
public class TestBrandsDto {
private String brandId;
private String partnerId;
private String brandName;
private String useyn;
private String brandName2;
}
스프링과 mapstruct 을 사용할 경우 componentModel = "spring"
을
반드시 붙여주어야 오류가 발생하지 않는다.
@Mapper(componentModel = "spring")
public interface TestBrandsMapper {
TestBrands toEntity(TestBrandsDto dto);
TestBrandsDto toDto(TestBrands entity);
}
일치하지 않는 필드 무시하기
ReportingPolicy.IGNORE
를 설정해서 일치하지 않는 필드를 무시할 수 있다.
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface TestBrandsMapper {
TestBrands toEntity(TestBrandsDto dto);
TestBrandsDto toDto(TestBrands entity);
}
무시할 필드를 명시할 수 있다.
@Mapper(componentModel = "spring")
public interface TestBrandsMapper {
@Mapping(target = "partnerId2", ignore = true)
@Mapping(target = "useyn", ignore = true)
TestBrands toEntity(TestBrandsDto dto);
@Mapping(target = "brandName2", ignore = true)
@Mapping(target = "useyn", ignore = true)
TestBrandsDto toDto(TestBrands entity);
}
일치하지 않는 필드를 수동으로 매핑
@Mapper(componentModel = "spring")
public interface TestBrandsMapper {
@Mapping(source = "partnerId", target = "partnerId2")
@Mapping(target = "useyn", ignore = true)
TestBrands toEntity(TestBrandsDto dto);
@Mapping(source = "brandName", target = "brandName2")
@Mapping(target = "useyn", ignore = true)
TestBrandsDto toDto(TestBrands entity);
}