【问题标题】:How to ignore mapping a property of a list of objects如何忽略映射对象列表的属性
【发布时间】:2021-12-15 03:02:54
【问题描述】:

我正在使用 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);

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    我看到了两个选项。

    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 参数以及指向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);
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多