【问题标题】:MapStruct mapping to unmodifiable model classMapStruct 映射到不可修改的模型类
【发布时间】:2021-12-29 23:33:04
【问题描述】:

我正在使用一个库中的模型,该模型具有多个构造函数,并且没有一个是无参数的。所以编译失败说

either declare parameterless constructor or annotate the default constructor with an annotation named @Default

但正如我所说,我无法修改模型,因为它来自另一个库。是否有任何解决方案,以便我可以使用 mapstruct 映射具有多个构造函数的模型,这些构造函数都不是无参数的。

版本详情

依赖关系

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.4.2.Final</version>
</dependency>

插件

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <source>11</source>
            <target>11</target>
            <annotationProcessorPaths>
                <path>
                    <groupId>org.mapstruct</groupId>
                    <artifactId>mapstruct-processor</artifactId>
                    <version>1.4.2.Final</version>
                </path>
            </annotationProcessorPaths>
        </configuration>
    </plugin>

【问题讨论】:

  • 所以编译失败说 - 编译什么?
  • 使用mapstruct&mapstruct插件的应用编译。
  • 你不觉得代码有问题吗?如果是这样,您认为向您要求帮助您的人展示该代码没有用吗?
  • 这不是代码特定的问题。只读类有多个构造函数,每个构造函数都有参数。在这种情况下,mapstruct 默认不能映射。它需要非参数化构造函数或只有一个参数化构造函数。所以问,在这种情况下是否有办法实现映射。

标签: java spring spring-boot dictionary mapstruct


【解决方案1】:

Mapstruct 通过Object Factories 支持这一点。检查他们的文档。

这是他们那里的代码。您可以根据需要使用工厂来初始化对象,因为它们没有默认构造函数。

public class DtoFactory {

     public CarDto createCarDto() {
         return // ... custom factory logic
     }
}
public class EntityFactory {

     public <T extends BaseEntity> T createEntity(@TargetType Class<T> entityClass) {
         return // ... custom factory logic
     }
}
@Mapper(uses= { DtoFactory.class, EntityFactory.class } )
public interface CarMapper {

    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );

    CarDto carToCarDto(Car car);

    Car carDtoToCar(CarDto carDto);
}
//GENERATED CODE
public class CarMapperImpl implements CarMapper {

    private final DtoFactory dtoFactory = new DtoFactory();

    private final EntityFactory entityFactory = new EntityFactory();

    @Override
    public CarDto carToCarDto(Car car) {
        if ( car == null ) {
            return null;
        }

        CarDto carDto = dtoFactory.createCarDto();

        //map properties...

        return carDto;
    }

    @Override
    public Car carDtoToCar(CarDto carDto) {
        if ( carDto == null ) {
            return null;
        }

        Car car = entityFactory.createEntity( Car.class );

        //map properties...

        return car;
    }
}

而且您始终可以通过添加custom methods 来添加自己的映射逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多