MapStruct嵌套对象的复制
准备
类A
1 2 3 4 5 6 7 8
| @Data @NoArgsConstructor @AllArgsConstructor public class A { String name; String age; B b; }
|
类B
1 2 3 4 5 6 7
| @Data @NoArgsConstructor @AllArgsConstructor public class B { String title; String content; }
|
DTO对象
1 2 3 4 5 6 7 8
| @Data @NoArgsConstructor @AllArgsConstructor public class ADTO { String name; String age; BDTO b; }
|
1 2 3 4 5
| @Data public class BDTO { String titleB; String contentB; }
|
转换
现有A对象
1
| A(name=name, age=18, b=B(title=title, content=content))
|
需要复制到ADTO对象中
使用 AMapper
1 2 3 4 5 6
| @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface AMapper { A toEntity(ADTO adto);
ADTO toDTO(A a); }
|
得到结果
1
| ADTO(name=name, age=18, b=BDTO(titleB=null, contentB=null))
|
不能得到正确的映射结果
解决
使用
1 2 3 4 5 6
| @Mapper(uses = BMapper.class, unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface AMapper { A toEntity(ADTO adto);
ADTO toDTO(A a); }
|
使用uses属性指定使用到的 mappers,可以自动完成映射。BMapper内容如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface BMapper { @Mappings({ @Mapping(source = "titleB", target = "title"), @Mapping(source = "contentB", target = "content") }) B toEntity(BDTO adto);
@Mappings({ @Mapping(source = "title", target = "titleB"), @Mapping(source = "content", target = "contentB") }) BDTO toDTO(B a); }
|
结果
1 2
| A(name=name, age=18, b=B(title=title, content=content)) ADTO(name=name, age=18, b=BDTO(titleB=title, contentB=content))
|
结论
MapStruct @Mapper使用uses属性指定使用到的 mappers,可以自动完成映射。