有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Mapstruct集合映射器中使用修饰方法?

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

我在decorator as specified in the doc中的一个方法中添加了一些DTO的附加处理

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

然而,生成的集合映射方法并没有使用修饰的方法来映射每个实体,只是在委托上使用“香草”生成的方法。以下是生成的方法的代码:

@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__;
}

。。。并且从不为集合中的项目调用装饰方法

除了在我的decorator中手动编写收集方法(虽然可以工作,但很冗长,并且违背了让Mapstruct首先不必编写此类代码的目的),还有什么方法可以让Mapstruct在集合映射中使用decorator方法


共 (1) 个答案

  1. # 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 {
        ...
    }