如何在MapStruct的源映射中禁用字段?

时间:2019-02-25 09:45:01

标签: java mapstruct

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

我要映射的课程,其中

@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是不可行的。有什么建议吗?

1 个答案:

答案 0 :(得分: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会为您生成一个列表映射。如果您需要外部列表,则可能不需要限定符。 。通用+列表就足够了