【问题标题】:How can I disable a field in source mapping in MapStruct?如何在 MapStruct 的源映射中禁用字段?
【发布时间】:2019-02-26 06:33:19
【问题描述】:

例如,我有一个带有字段的映射类,该字段未在映射类中显示。

一个类,哪个我想映射:

@Entity
@Table(name = "t_connection")
@Getter @Setter
@EqualsAndHashCode
public class ConnectionEntity {
    @NotNull
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    protected UUID id;
...
}

一个类,我想在其中进行映射

@ApiModel
@Getter
@Setter
@NoArgsConstructor
public class ConnectionDto {
    @ApiModelProperty
    private LocalDateTime createAt;
...
// Other fields without id field
}

我的映射器如下所示:

@Mapper(componentModel = "spring",
        unmappedTargetPolicy = ReportingPolicy.ERROR,
        unmappedSourcePolicy = ReportingPolicy.ERROR)
public interface CallMapper {

    @IterableMapping(qualifiedByName = "map")
    List<ConnectionDto> map(List<ConnectionEntity> connectionEntities);

    ConnectionDto map(ConnectionEntity connectionEntity);
}

我想知道,当没有映射特定字段时,禁用unmappedSourcePolicy 不是一个选项。有什么建议吗?

【问题讨论】:

  • 这似乎是不可能的,有一种相当愚蠢的方法就是手写map()default ConnectionDto map(ConnectionEntity connectionEntity) { ConnectionDto dto = new ConnectionDto(); dto.set ... (connectionEntity.get... ); return dto; }
  • 有可能。感谢@sjaak。看到那个答案:stackoverflow.com/a/54875713/11112760

标签: java mapstruct


【解决方案1】:

如果我理解你的话.. 你想控制你不想映射的源属性吗?

在这种情况下尝试:

@BeanMapping#ignoreUnmappedSourceProperties

所以:

@Mapper(componentModel = "spring",
        unmappedTargetPolicy = ReportingPolicy.ERROR,
        unmappedSourcePolicy = ReportingPolicy.ERROR)
public interface CallMapper {

    @IterableMapping(qualifiedByName = "map")
    List<ConnectionDto> map(List<ConnectionEntity> connectionEntities);

    @BeanMapping( ignoreUnmappedSourceProperties={"id"} )
    ConnectionDto map(ConnectionEntity connectionEntity);
}

您不需要指定列表映射,除非您从外部需要它.. MapStruct 将为您生成一个.. 如果您确实需要来自外部的列表,您可能不需要限定符。 . Generic + List 就够了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2018-09-06
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多