PageInfoDto
public class PageInfoDto<T> implements Serializable {
private int currentPageNum;
private int totalPageNum;
private int perPageNum;
private int totalItemNum;
private List<T> list;
}
页面
public class Page<T> implements Serializable {
private int current;
private int total;
private int size;
private int items;
private List<T> list;
}
说,我有一个学校名单和一个学生名单。
我想将Page映射到PageInfoDto并将Page映射到PageInfoDto。
这就是我的映射器的样子;
@Mapper( config = CentralConfig.class, uses = {StudentMapper.class, SchoolMapper.class}, componentModel = "spring")
public interface PageInfoMapper {
@Mappings({
@Mapping(target = "list", source = "pageInfo.records"),
@Mapping(target = "currentPageNum", source = "pageInfo.current"),
@Mapping(target = "totalPageNum", source = "pageInfo.pages"),
@Mapping(target = "perPageNum", source = "pageInfo.size"),
@Mapping(target = "totalItemNum", source = "pageInfo.total"),
})
PageInfoDto<SchoolDto> toPageInfoDto1(Page<School> pageInfo);
@Mappings({
@Mapping(target = "list", source = "pageInfo.records"),
@Mapping(target = "currentPageNum", source = "pageInfo.current"),
@Mapping(target = "totalPageNum", source = "pageInfo.pages"),
@Mapping(target = "perPageNum", source = "pageInfo.size"),
@Mapping(target = "totalItemNum", source = "pageInfo.total"),
})
PageInfoDto<StudentDto> toPageInfoDto2(Page<Student> pageInfo);
}
这显然不是一个聪明的方法。有更好的方法吗?
答案 0 :(得分:1)
Mapstruct是代码生成器。因此,它需要知道构造哪些类型才能生成方法实现。话虽这么说,您可以通过使用基本映射方法(在此方法上定义所有@Mapping
批注并忽略通用类型映射)来更智能地做到这一点。您仍然可以使用上述方法,但只需指定@InheritConfiguration
或者,您可以考虑使用@TargetType
与对象工厂一起构建正确的泛型类型。我不确定这是否适用于通用映射方法签名。我无法检查它,但请告诉我是否可行
例如
public interface BasePageMapper<S, DTO> {
@Mapping(target = "list", source = "records"),
@Mapping(target = "currentPageNum", source = "current"),
@Mapping(target = "totalPageNum", source = "pages"),
@Mapping(target = "perPageNum", source = "size"),
@Mapping(target = "totalItemNum", source = "total"),
PageInfoDto<DTO> toPageInfoDto(Page<S> pageInfo);
DTO toDto(S source);
}
@Mapper( config = CentralConfig.class, uses = StudentMapper.class, componentModel = "spring")
public interface StudentMapper extends BasePageMapper<Student, StudentDto> {
}
@Mapper( config = CentralConfig.class, uses = SchoolMapper.class, componentModel = "spring")
public interface SchoolMapper extends BasePageMapper<School, SchoolDto> {
}