본문 바로가기
Spring/series

[spring 21편] mapstruct 활용 2번째 (expression 사용)

by 무대포 개발자 2023. 1. 21.
728x90
반응형

source 는 Github 에 있습니다.

목차는 spring series 목차 에 있습니다.

[spring 21편] mapstruct 활용 2번째 (expression 사용)

mapstruct expression 활용

  • expression 을 통해 source list --> target list 으로 convert 하는 예제를 정리했습니다.

Source

// ItemInfoMapper.java
@Mapper(
componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
unmappedTargetPolicy = ReportingPolicy.ERROR
)
public interface ItemInfoMapper {
ItemInfoMapper INSTANCE = Mappers.getMapper(ItemInfoMapper.class);
@Mapping(source = "id", target = "itemId")
@Mapping(expression = "java(Item.resolveDescList(item))", target = "descList")
ItemInfo.Base of(Item item);
}
// Item.java
@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Item {
@Id
private String id;
@Column
private String itemName;
private List<ItemDescription> descriptionList;
public static List<ItemInfo.Sub> resolveDescList(final Item item) {
return item.getDescriptionList().stream().map(desc ->
ItemInfo.Sub.builder()
.desc1(desc.getDesc1())
.desc2(desc.getDesc2())
.desc3(desc.getDesc3())
.build()
).collect(Collectors.toList());
}
;
@Data
@AllArgsConstructor
@Builder
public static class ItemDescription {
private String desc1;
private String desc2;
private String desc3;
}
}
// ItemInfo.java
public class ItemInfo {
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class Base {
private String itemId;
private String itemName;
List<Sub> descList;
}
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public static class Sub extends SuperSub {
private String etc1;
}
@NoArgsConstructor
@AllArgsConstructor
@Data
@SuperBuilder
public static class SuperSub {
private String desc1;
private String desc2;
private String desc3;
}
}
// ItemInfoMapperTest.java
public class ItemInfoMapperTest {
@Test
void testItemInfoMapperTest() {
final var item = Item.builder()
.id("10")
.itemName("testItem")
.descriptionList(List.of(
Item.ItemDescription.builder()
.desc1("desc1")
.desc2("desc2")
.desc3("desc3")
.build(),
Item.ItemDescription.builder()
.desc1("desc11")
.desc2("desc22")
.desc3("desc33")
.build()
))
.build();
final ItemInfo.Base result = ItemInfoMapper.INSTANCE.of(item);
final ItemInfo.Base expected = getExpected();
Assertions.assertEquals(result, expected);
}
private ItemInfo.Base getExpected() {
final var expected = ItemInfo.Base.builder()
.itemId("10")
.itemName("testItem")
.descList(List.of(
ItemInfo.Sub.builder()
.desc1("desc1")
.desc2("desc2")
.desc3("desc3")
.build(),
ItemInfo.Sub.builder()
.desc1("desc11")
.desc2("desc22")
.desc3("desc33")
.build()))
.build();
return expected;
}
}

댓글