【发布时间】:2022-01-07 03:08:00
【问题描述】:
BaseDto:
@Data
@NoArgsConstructor
@SuperBuilder
public class BaseDto{
// Some fields
}
TestDto:
@Data
@NoArgsConstructor
@SuperBuilder
public class TestDto extends BaseDto {
// Some fields
}
基础映射器:
@MapperConfig(
componentModel = "spring"
)
public interface BaseMapper<E extends BaseEntity, DTO extends BaseDto> {
DTO toDto(E entity);
....
}
Mapper 生成 Impl:
@Component
public class TestMapperImpl implements BaseMapper {
@Override
public TestDto toDTO(Test entity) {
BaseDtoBuilder<?, ?> testDto= BaseDto.builder();
if ( entity != null ) {
if ( entity.getId() != null ) {
testDto.id(entity.getId() );
}
}
return testDto.build();
}
}
Mapper 自动创建 Impl 类。问题是返回类型。
BaseDtoBuilder<?, ?> testDto= BaseDto.builder();
return testDto.build();
Intelij 给出错误返回类型,它必须强制转换为 TestDto。因为映射器返回 BaseDto。我该如何解决这个问题?
注意:如果使用@Builder,没有错误工作正常,这次我无法访问父属性。
【问题讨论】:
-
你不能有泛型
@Mappers ...你可以有“类型化”@Mappers 扩展泛型基类/接口..:stackoverflow.com/q/57351869/592355
标签: spring spring-boot base mapstruct mapper