我找到了如何用装饰器实现它,谢谢@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
映射器
@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");
}
}
装饰者
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;
}
}
我使用abstract class
, 不interface
用于映射器,因为如果interface
您无法排除生成方法map(List<Child> children, Parent parent)
,并且生成的代码在编译时无效。