Ale*_*exB 7 java mapping mapstruct
假设我有这样的映射:
@Mapping(source = "parentId", target = "parent.id")
Child map(ChildDto dto, Parent parent);
Run Code Online (Sandbox Code Playgroud)
现在我需要将 ChildDto 列表映射到 Child 列表,但它们都具有相同的父级。我希望做这样的事情:
List<Child> map(List<ChildDto> dtoList, Parent parent);
Run Code Online (Sandbox Code Playgroud)
但它不起作用。有机会做到吗?
我找到了如何用装饰器实现它,谢谢@Gunnar 这是一个实现:
public class Child {
int id;
String name;
}
public class Parent {
int id;
String name;
}
public class ChildDto {
int id;
String name;
int parentId;
String parentName;
}
// getters/settes ommited
Run Code Online (Sandbox Code Playgroud)
@Mapper
@DecoratedWith(ChildMapperDecorator.class)
public abstract class ChildMapper {
public static final ChildMapper INSTANCE = Mappers.getMapper(ChildMapper.class);
@Mappings({
@Mapping(target = "parentId", ignore = true),
@Mapping(target = "parentName", ignore = true)
})
@Named("toDto")
abstract ChildDto map(Child child);
@Mappings({
@Mapping(target = "id", ignore = true),
@Mapping(target = "name", ignore = true),
@Mapping(target = "parentId", source = "id"),
@Mapping(target = "parentName", source = "name")
})
abstract ChildDto map(@MappingTarget ChildDto dto, Parent parent);
@IterableMapping(qualifiedByName = "toDto") // won't work without it
abstract List<ChildDto> map(List<Child> children);
List<ChildDto> map(List<Child> children, Parent parent) {
throw new UnsupportedOperationException("Not implemented");
}
}
Run Code Online (Sandbox Code Playgroud)
public abstract class ChildMapperDecorator extends ChildMapper {
private final ChildMapper delegate;
protected ChildMapperDecorator(ChildMapper delegate) {
this.delegate = delegate;
}
@Override
public List<ChildDto> map(List<Child> children, Parent parent) {
List<ChildDto> dtoList = delegate.map(children);
for (ChildDto childDto : dtoList) {
delegate.map(childDto, parent);
}
return dtoList;
}
}
Run Code Online (Sandbox Code Playgroud)
我使用abstract class, 不interface用于映射器,因为如果interface您无法排除生成方法map(List<Child> children, Parent parent),并且生成的代码在编译时无效。
| 归档时间: |
|
| 查看次数: |
32485 次 |
| 最近记录: |