Mapstruct 不会自动映射基类型构造函数

Mapstruct does not automatically map the base type constructor

环境: java: 17.0.1 映射结构:1.4.2.Final

示例:

public record RecordId(Long id) {
}

映射器

@Mapper(componentModel = "spring")
public interface RecordIdAssembler {

    @Mapping(target = "id")
    RecordId convertRecord(Long id);

    @Mapping(source = "id",target = ".")
    Long convertRecord(RecordId id);

    List<RecordId> convertRecord(List<Long> id);
}

但是编译出错

java: Ambiguous constructors found for creating java.lang.Long. Either declare parameterless constructor or annotate the default constructor with an annotation named @Default.

无法修改Long类型的构造函数

我应该如何配置它?

您在这里处理的不是映射,而是容器对象(包含单个字段的对象)。最好手动实现这个,列表映射可以用 mapstruct 实现。

@Mapper(componentModel = "spring")
public interface RecordIdAssembler {
    default RecordId convertRecord(Long id) {
        return new RecordId(id);
    }

    default Long convertRecord(RecordId id) {
        return id.id();
    }
    List<RecordId> convertToRecord(List<Long> id);
    List<Long> convertFromRecord(List<RecordId> id);
}

另一种选择是在将 RecordIdLong 作为字段的情况下处理此问题,并使用映射转换它们。例如在下面的情况下:

class RecordDto {
  private Long id;
// other fields
// getters & setters
}
class RecordEntity {
  private RecordId recId;
// other fields
// getters & setters
}
@Mapper
interface RecordMapper {
  @Mapping(source = "id", target = "recId.id");
  RecordEntity map(RecordDto dto);

  @InheritInverseConfiguration
  RecordDto map(RecordEntity entity);
}