如何忽略映射对象列表的 属性

How to ignore mapping a property of a list of objects

我正在使用 MapStruct 库来促进对象之间的映射。我有一个问题,忽略不映射列表中某些对象的某个 属性。

在对象 CompetitionEntity 中,我有这个 属性 列表:

private List<GameEntity> games;

在 GameEntity 中,我有这个

private TeamEntity visitorTeam;

当我进行从 CompetitionEntity 到 CopmpetitionDto 的映射时,我想忽略它映射对象 visitorTeam。我尝试执行以下操作,但它不起作用。

@Mapper
public interface CompetitionMapper {

@Mapping(target = "games.localTeam", ignore = true)
@Mapping(target = "games.visitorTeam", ignore = true)
@Mapping(target = "games.competition", ignore = true)
CompetitionDto entityToDto(CompetitionEntity entity);

我看到两个选项。

  1. 如果此类映射规则应始终应用于 GameEntity

首先使用所需设置定义 GameMapper

@Mapper
public interface GameMapper {

    @Mapping(target = "localTeam", ignore = true)
    @Mapping(target = "visitorTeam", ignore = true)
    @Mapping(target = "competition", ignore = true)
    GameDto entityToDto(GameEntity entity);
}

然后在 CompetitionMapper 添加 uses 参数 link 到 GameMapper 。这意味着 CompetitionMapper 将在映射 GameEntity:

时使用 GameMapper 中的方法
@Mapper(uses = GameMapper.class)
public interface CompetitionMapper {

    CompetitionDto entityToDto(CompetitionEntity entity);

}
  1. 如果此类映射仅应在 CompetitionEntity 的上下文中应用于 GameEntity

CompetitionMapper 中定义辅助方法并与 quelifiedBy 一起使用。

@Mapper
public interface CompetitionMapper {

    @Mapping(target = "games", qualifiedByName = "gameMapper")
    CompetitionDto entityToDto(CompetitionEntity entity);

    @Named("gameMapper")
    @Mapping(target = "localTeam", ignore = true)
    @Mapping(target = "visitorTeam", ignore = true)
    @Mapping(target = "competition", ignore = true)
    GameDto entityToDto(GameEntity entity);
}