【问题标题】:MapStruct @SuperBuilder Return type error not castMapStruct @SuperBuilder 返回类型错误未强制转换
【发布时间】: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,没有错误工作正常,这次我无法访问父属性。

【问题讨论】:

标签: spring spring-boot base mapstruct mapper


【解决方案1】:

我用这个配置解决了问题:MapStruct and Lombok not working together

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
    <source>${java.version}</source>
    <target>${java.version}</target>
    <annotationProcessorPaths>
        <path>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${org.projectlombok.version}</version>
        </path>
        <!-- This is needed when using Lombok 1.18.16 and above -->
        <path>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok-mapstruct-binding</artifactId>
            <version>0.2.0</version>
        </path>
        <!-- Mapstruct should follow the lombok path(s) -->
        <path>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${org.mapstruct.version}</version>
        </path>
    </annotationProcessorPaths>
</configuration>
</plugin>

感谢您的帮助xerx593

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多