mapStruct 停止映射 DTO 的超级 class 字段的配置是什么?

what would be the configuration for mapStruct to stop mapping a DTO's super class's fields?

我有一个 DTO class,它正在扩展 spring-hateoasResourceSupport class。 UserMinimalDtoUser 实体的 DTO。

因此,为了生成映射器 classes,我使用 mapStruct

@Data //from lambok
@EqualsAndHashCode(callSuper=false)
public class UserMinimalDto extends ResourceSupport {

    String firstName;
    String lastName;
    String email;
    String uniqueId;
    String profilePicUrl;

}

我正在使用 ResourceSupport 将 hateoas 链接添加到控制器的响应中。

映射器接口

@Mapper
public interface UserMinimalMapper {

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

    UserMinimalDto entityToDto(User user);

    User dtoToEntity(UserMinimalDto userMinimalDto);
}

但是当我运行 mvn clean install 在项目上时,我遇到了编译错误

Can't map property "org.springframework.hateoas.Link id" to "java.lang.Integer id". Consider to declare/implement a mapping method: "java.lang.Integer map(org.springframework.hateoas.Link value)".

这是因为 mapStruct 正在尝试映射 ResourceSupport 的字段。 它的作品如果:

  1. 我从 UserMinimalDto
  2. 中删除了 extends ResourceSupport
  3. 我删除了 dtoToEntity(UserMinimalDto userMinimalDto);来自映射器 界面

告诉 mapStruct 不映射超级 class 字段的配置是什么?

这是因为模型 class 具有不同于 DTO 的其他字段集,并且您的映射器双向映射。但这很自然,dto 没有 id。

解决方法是从映射中排除这些字段,例如通过注释 id 和模型 class 中的其他字段,这些字段不在 dto 中:Mapping("this").

为了根据具体情况忽略字段,您可以使用 Mapping#ignore

在你的情况下它看起来像:

@Mapper
public interface UserMinimalMapper {

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

    UserMinimalDto entityToDto(User user);

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "links", ignore = true)
    User dtoToEntity(UserMinimalDto userMinimalDto);
}

如果您的实体有通用接口/class,您可以使用@MapperConfig并定义那些排除项。

它看起来像:

@MapperConfig(mappingInheritanceStrategy = MappingInheritanceStrategy.AUTO_INHERIT_FROM_CONFIG)
public interface CommonMappingConfig {

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "links", ignore = true)
    BaseEntity map(ResourceSupport resourceSupport);

}

@Mapper(config = CommonMappingConfig.class)
public interface UserMinimalMapper {

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

    UserMinimalDto entityToDto(User user);

    User dtoToEntity(UserMinimalDto userMinimalDto);
}