【问题标题】:How to use decorated method in Mapstruct collection mapper?如何在 Mapstruct 集合映射器中使用修饰方法?
【发布时间】:2016-09-12 03:41:03
【问题描述】:

我在使用依赖注入的 Spring 应用程序中使用 MapStruct 从 JPA 实体映射到 POJO DTO。

我在装饰器as specified in the doc 中的方法中添加了一些额外的DTO 处理。

它适用于映射单个实体。但我也有这些实体的集合(集合)的映射,当在关系中找到这些实体的集合时,会自动调用该方法。

但是生成的集合映射方法不使用装饰方法来映射每个实体,只是使用委托上的“vanilla”生成方法。这是生成方法的代码:

@Override
public Set<DimensionItemTreeDTO> missionSetToTreeDtoSet(Set<Mission> set)  {
    return delegate.missionSetToTreeDtoSet( set );
}

委托方法本身不知道装饰器并在其自身上调用单个项目映射方法:

@Override
public Set<DimensionItemTreeDTO> missionSetToTreeDtoSet(Set<Mission> set) {
    if ( set == null ) {
        return null;
    }

    Set<DimensionItemTreeDTO> set__ = new HashSet<DimensionItemTreeDTO>();
    for ( Mission mission : set ) {
        set__.add( missionToTreeDto( mission ) ); //here the decorator is not called !
    }

    return set__;
}

...并且永远不会为集合中的项目调用装饰方法。

有没有一种方法可以让 Mapstruct 在集合映射中使用装饰器方法,而不是在我的装饰器中手动编写集合方法(这可行但很冗长,并且违背了首先使用 MapStruct 的目的,而不是必须写这种代码)?

【问题讨论】:

    标签: java decorator mapstruct


    【解决方案1】:

    我找到了解决问题的方法:实际上我的用例更适合 MapStruct @AfterMapping methods,我使用了它,现在它适用于所有情况:

    @Mapper
    public abstract class ConstraintsPostProcessor {
    
        @Inject
        private UserService userService; // can use normal Spring DI here
    
        @AfterMapping
        public void setConstraintsOnMissionTreeDTO(Mission mission, @MappingTarget MissionDTO dto){ // do not forget the @MappingTarget annotation or it will not work
            dto.setUser(userService.getCurrentUser()); // can do any additional logic here, using services etc.
        }
    }
    

    在主映射器中:

    @Mapper(uses = {ConstraintsPostProcessor.class}) // just add the previous class here in the uses attribute
    public interface DimensionMapper {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-30
      • 2018-03-30
      • 2018-10-05
      • 2018-08-24
      • 2018-07-09
      • 2016-07-23
      • 2020-05-08
      • 2021-05-10
      相关资源
      最近更新 更多