【问题标题】:Prevent Cyclic references when converting with MapStruct使用 MapStruct 进行转换时防止循环引用
【发布时间】:2016-07-13 10:25:43
【问题描述】:

今天我开始使用 MapStruct 为我的项目创建模型到 DTO 转换器,我想知道它是否会自动处理循环引用,但事实证明它没有。

这是我用来测试的转换器:

package it.cdc.snp.services.rest.giudizio;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;

import it.cdc.snp.dto.entita.Avvisinotifica;
import it.cdc.snp.dto.entita.Corrispondenza;
import it.cdc.snp.model.notifica.AvvisoDiNotificaModel;
import it.cdc.snp.model.notifica.NotificaModel;
import it.cdc.snp.model.procedimento.ProcedimentoModel;

@Component
@Mapper(componentModel="spring")
public interface NotificaMapper {

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

    @Mappings({
        @Mapping(source = "avvisinotificas", target = "avvisinotificas"),
    })
    NotificaModel<ProcedimentoModel> corrispondenzaToNotificaModel(Corrispondenza notifica);

    @Mappings({
        @Mapping(source = "corrispondenza", target = "notifica"),
    })
    AvvisoDiNotificaModel avvisinotificaToAvvisoDiNotificaModel(Avvisinotifica avvisinotifica);


}

这是测试:

        Notifica sourceObject1 = new Notifica();
        sourceObject1.setId(new Long(1));
        Avvisinotifica sourceObject2 = new Avvisinotifica();
        sourceObject2.setId(new Long(11));
        List<Avvisinotifica> tests= new ArrayList<>();
        tests.add(sourceObject2);
        sourceObject1.setAvvisinotificas(tests);
        sourceObject2.setCorrispondenza(sourceObject1);

        NotificaModel destObject1 = new NotificaModel<>();
        Avvisinotifica destObject2 = new Avvisinotifica();

        NotificaModel converted = mapper.corrispondenzaToNotificaModel(sourceObject1);

Notifica、Avvisinotifica 和它们各自的模型都是带有 setter 和 getter 的简单 POJO,所以我认为不需要发布代码(Notifica 扩展了 Corrispondenza,如果您想知道的话)

这段代码进入了一个无限循环,这并不奇怪(尽管我希望它能处理这些情况)。 虽然我认为我可以找到一种优雅的方法来手动处理它(我正在考虑使用 @MappingTarget 的方法来插入引用的对象),但我想知道是否有某种方法可以告诉 MapStruct 如何自动处理循环引用。

【问题讨论】:

    标签: java cyclic-reference mapstruct


    【解决方案1】:

    Notifica 和 Avvisinotifica 无法帮助我理解您的模型。因此,假设您有上述 Child 和 Father 模型,

    public class Child {
        private int id;
        private Father father;
        // Empty constructor and getter/setter methods omitted.
    }
    
    public class Father {
        private int x;
        private List<Child> children;
        // Empty constructor and getter/setter methods omitted.
    }
    
    public class ChildDto {
        private int id;
        private FatherDto father;
        // Empty constructor and getter/setter methods omitted.
    }
    
    public class FatherDto {
        private int id;
        private List<ChildDto> children;
        // Empty constructor and getter/setter methods omitted.
    }  
    

    你应该像这样创建一个映射器,

    @Mapper
    public abstract class ChildMapper {
    
        @AfterMapping
        protected void ignoreFathersChildren(Child child, @MappingTarget ChildDto childDto) {
            childDto.getFather().setChildren(null);
        }
    
        public abstract ChildDto myMethod(Child child);
    }
    

    === Mapstuct 初始版本

    最好遵循以下方法。此解决方案假定 ChildDto::father 属性的类型为 Father,而不是 FatherDto,这不是正确的数据架构。
    @AfterMapping 注解意味着该方法将在属性映射后导入到生成的源中。因此,Mapper 的实现会是这样的,

    @Component
    public class ChildMapperImpl extends ChildMapper {
    
        @Override
        public ChildDto myMethod(Child child) {
            if ( child == null ) {
                return null;
            }
    
            ChildDto childDto = new ChildDto();
    
            childDto.setId( child.getId() );
            childDto.setFather( child.getFather() );
    
            ignoreFathersChildren( child, childDto );
    
            return childDto;
        }
    }
    

    在这个实现中,孩子拥有父母集。这意味着存在循环引用,但使用ignoreFathersChildren(child, childDto) 方法我们删除了引用(我们将其设置为空)。

    === 更新 1

    使用 mapstruct 版本 1.2.0.Final 你可以做得更好,

    @Mapper
    public interface ChildMapper {
    
        @Mappings({
    //         @Mapping(target = "father", expression = "java(null)"),
             @Mapping(target = "father", qualifiedByName = "fatherToFatherDto")})
        ChildDto childToChildDto(Child child);
    
        @Named("fatherToFatherDto")
        @Mappings({
             @Mapping(target = "children", expression = "java(null)")})
        FatherDto fatherToFatherDto(Father father);
    }
    

    === 更新 2

    使用 mapstruct 版本 1.4.2.Final 你可以做得更好,

    @Named("FatherMapper")
    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
    public interface FatherMapper {
    
        @Named("toDto")
        @Mappings
        FatherDto toDto(Father father);
    
        @Named("toDtoWithoutChildren")
        @Mappings({
             @Mapping(target = "children", expression = "java(null)")})
        FatherDto toDtoWithoutChildren(Father father);
    }
    
    @Named("ChildMapper")
    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, uses = {FatherMapper.class})
    public interface ChildMapper {
    
        @Named("toDto")
        @Mappings({
             @Mapping(target = "father", qualifiedByName = {"FatherMapper", "toDtoWithoutChildren"})})
        ChildDto toDto(Child child);
    
        @Named("toDtoWithoutFather")
        @Mappings({
             @Mapping(target = "father", expression = "java(null)")})
        ChildDto toDtoWithoutFather(Child child);
    }
    

    【讨论】:

    • 从 MapStruct 1.2.0.Beta1(昨天发布)开始,另一种可能的方法是使用上下文参数来跟踪已映射的对象。你可以找到一个完整的例子来展示如何做到这一点here
    • 那我该怎么处理 Context 的东西?怎么实例化,调用mapper方法的时候传到哪里?
    • 不使用expression="java(null)",可以使用ignore = true
    • 不应该FatherDtoList&lt;ChildDto&gt; 而不是List&lt;Child&gt;
    • childDto.setFath 期望的是 FatherDto,而不是父亲
    【解决方案2】:

    实际上,这种带有 CycleAvoidingMappingContext 的方法对我使用 MapStruct 版本 1.3.1 时不起作用。由于我找不到太多可行的示例,因此我特意在此处发布我的解决方案以供其他人查找。

    在双向关系的情况下,此类映射可能会由于循环引用而触发 StackOverflowError。

    示例:类 Recipe、Book 和 Ingredient 以一对多和多对多双向关联。

    • 一个食谱有很多成分,但只在一本书中提及。
    • 一本书里有很多食谱。
    • 一种成分仅用于一种配方(假设一种成分还具有固定其数量、计量单位等的属性,因此它确实仅适用于一种配方)。
        public class Recipe {
            Long id;
            // ... Other recipe properties go here
            Book book;
            Set<Ingredient> ingredients;
        }
        
        public class Book {
            Long id;
            // ... Other book properties go here
            Set<Recipe> recipes;
        }
        
        public class Ingredient {
            Long id;
            // ... Other ingredient properties go here
            Recipe recipe;
        }
    

    我假设您也会有具有相同属性的 DTO 类,但当然是指它们相应的 DTO 类。

    这些将是从实体类映射到 DTO 类的默认 Mapper 设置(在这种情况下不依赖于 Spring):

    // MapStruct can handle primitive and standard classes like String and Integer just fine, but if you are using custom complex objects it needs some instructions on how it should map these
        @Mapper(uses = {BookMapper.class, IngredientMapper.class})
        public interface RecipeMapper {
            RecipeMapper INSTANCE = Mappers.getMapper( RecipeMapper.class );
    
            RecipeDTO toDTO(Recipe recipe);
    
            Recipe toEntity(RecipeDTO recipeDTO);
        }
    
        @Mapper(uses = {RecipeMapper.class, IngredientMapper.class})
        public interface BookMapper {
            BookMapper INSTANCE = Mappers.getMapper( BookMapper.class );
    
            BookDTO toDTO(Book book);
    
            Book toEntity(BookDTO book);
        }
    
        @Mapper(uses = {RecipeMapper.class, BookMapper.class})
        public interface IngredientMapper {
            IngredientMapper INSTANCE = Mappers.getMapper( IngredientMapper.class );
    
            IngredientDTO toDTO(Ingredient ingredient);
    
            Ingredient toEntity(IngredientDTO ingredientDTO);
        }
    

    如果您停在那里并尝试以这种方式映射类,由于您现在定义的循环引用,您将受到 StackOverflowError 的打击(配方包含具有属性配方的成分...)。 只有在没有会触发反向映射的双向关系时才能使用这种默认的 Mapper 设置。

    你可以这样写 A -> B -> A -> B -> A ... 关于对象映射,我的经验表明,您应该能够将其映射为:A -> B -> A(不包括这次打破循环的关系) 对于实体到 DTO 和 DTO 到实体的映射。这使您能够:

    • 深入到前端的关联对象:例如。显示食谱的成分列表
    • 保存对象时保持反向关系:例如。如果您只映射 A -> B。RecipeDTO 中的成分 DTO 将没有配方属性,并且在保存成分时,您需要将配方 ID 作为参数传递并跳过一些环以将成分实体对象与将成分实体保存到数据库之前的配方实体对象。

    定义 A -> B -> A 之类的映射(这次不包括关系以打破循环)将归结为定义单独的映射,以便在您想要从映射中排除相关的复杂对象时想要打破这个循环。

    @IterableMapping(qualifiedByName = "") 用于映射复杂对象的集合,指的是对单个复杂对象的映射。

    @Mapping(target = "PropertyName",qualifiedByName = "") 在映射复杂对象的集合时(当你想打破循环时),可用于指向排除逆向关系的替代映射

    @Mapping(target = "[.]", ignore = true) 可用于指示对象的属性根本不应该被映射。因此,这可以用来完全忽略一个(集合)复杂对象,或者在不需要时直接忽略单个(不是集合)相关复杂对象内部的属性。

    如果您不使用 qualifiedByName 属性和匹配的 @Named() 注释,您的映射将不会编译,并出现关于不明确映射的错误 如果 Mapper 接口中有多个返回类型和输入参数类型相同的方法。

    如果您使用命名映射,最好使用与@Named 注释值匹配的方法名称。

    因此,我们将首先记下想要的行为,然后对其进行编码:

    1. When mapping a Recipe, we will need to map the book property in such a way that its inverse relation to recipes is mapped without the book property the second time
        Recipe A -> Book X  -> Recipe A (without book property value as this would close the cycle)
            -> Recipe B (without book property value, as same mapping is used for all these recipes unfortunately as we don't know up front which one will cause the cyclic reference)...
                -> Ingredients I (without recipe property value as they would all point back to A)
                                 
    2. When mapping a Book, we will need to map the recipes property in such a way that its inverse relation to book isn't mapped as it will point back to the same book.
            Book X -> Recipe A (without book property as this would close the cycle)
                        -> Ingredients (without recipe property as all these will point back to Recipe A)
                            -> Recipe B (without book property, as same mapping is used for all these and all could potentially close the cycle)
                            -> Recipe C
                    
    3. When mapping an Ingredient, we will need to map the recipe property in such a way that its inverse relation to ingredient isn't mapped as one of those ingredients will point back to the same ingredient
    

    recipe 中的 book 属性需要在没有 recipes 属性的情况下进行映射,因为其中之一也会循环回 recipe。

        @Mapper(uses = {BookMapper.class, IngredientMapper.class})
        public interface RecipeMapper {
            RecipeMapper INSTANCE = Mappers.getMapper( RecipeMapper.class );
    
            @Named("RecipeSetIgnoreBookAndIngredientChildRecipes")
            @IterableMapping(qualifiedByName = "RecipeIgnoreBookAndIngredientChildRecipes")
            Set<RecipeDTO> toDTOSetIgnoreBookAndIngredientChildRecipes(Set<Recipe> recipes);
    
            @Named("RecipeSetIgnoreIngredientsAndBookChildRecipe")
            @IterableMapping(qualifiedByName = "RecipeIgnoreIngredientsAndBookChildRecipe")
            Set<RecipeDTO> toDTOSetIgnoreIngredientsAndBookChildRecipe(Set<Recipe> recipes);
                                    
            // In this mapping we will ignore the book property and the recipe property of the Ingredients to break the mapping cyclic references when we are mapping a book object
            // Don't forget to add the matching inverse mapping from DTO to Entity, this is basically just a copy with switch input parameter and return types
            @Named("RecipeIgnoreBookAndIngredientChildRecipes")
            @Mappings({
                @Mapping(target = "book", ignore = true),                                               // book is a single custom complex object (not a collection), so we can directly ignore its child properties from there
                @Mapping(target = "ingredients", qualifiedByName = "IngredientSetIgnoreRecipes"),       // ingredients is a collection of complex objects, so we can't directly ignore its child properties as in the end, a Mapper needs to be defined to Map a single POJO into another
            })
            RecipeDTO toDTOIgnoreBookAndIngredientChildRecipes(Recipe recipe);
    
            @Named("RecipeIgnoreIngredientsAndBookChildRecipe")
            @Mappings({
                @Mapping(target = "book.recipes", ignore = true),
                @Mapping(target = "ingredients", ignore = true),
            })
            RecipeDTO toDTOIgnoreIngredientsAndBookChildRecipe(Recipe recipe);
    
            // Don't forget to add the matching inverse mapping from DTO to Entity, this is basically just a copy with switch input parameter and return types
            @Mappings({
                @Mapping(target = "book.recipes", ignore = true),                                       // book is a single custom complex object (not a collection), so we can directly ignore its child properties from there
                @Mapping(target = "ingredients", qualifiedByName = "IngredientSetIgnoreRecipes"),       // ingredients is a collection of complex objects, so we can't directly ignore its child properties as in the end, a Mapper needs to be defined to Map a single POJO into another
            })
            RecipeDTO toDTO(Recipe recipe);
            
            @Named("RecipeSetIgnoreBookAndIngredientChildRecipes")
            @IterableMapping(qualifiedByName = "RecipeIgnoreBookAndIngredientChildRecipes")
            Set<Recipe> toEntitySetIgnoreBookAndIngredientChildRecipes(Set<RecipeDTO> recipeDTOs);
            
            @Named("RecipeSetIgnoreIngredientsAndBookChildRecipe")
            @IterableMapping(qualifiedByName = "RecipeIgnoreIngredientsAndBookChildRecipe")
            Set<Recipe> toEntitySetIgnoreIngredientsAndBookChildRecipe(Set<RecipeDTO> recipeDTOs);
            
            @Mappings({
                @Mapping(target = "book.recipes", ignore = true),                                       // book is a single custom complex object (not a collection), so we can directly ignore its child properties from there
                @Mapping(target = "ingredients", qualifiedByName = "IngredientSetIgnoreRecipes"),       // ingredients is a collection of complex objects, so we can't directly ignore its child properties as in the end, a Mapper needs to be defined to Map a single POJO into another
            })
            Recipe toEntity(RecipeDTO recipeDTO);
            
            @Named("RecipeIgnoreBookAndIngredientChildRecipes")
            @Mappings({
                @Mapping(target = "book", ignore = true),                                               // book is a single custom complex object (not a collection), so we can directly ignore its child properties from there
                @Mapping(target = "ingredients", qualifiedByName = "IngredientSetIgnoreRecipes"),       // ingredients is a collection of complex objects, so we can't directly ignore its child properties as in the end, a Mapper needs to be defined to Map a single POJO into another
            })
            Recipe toEntityIgnoreBookAndIngredientChildRecipes(RecipeDTO recipeDTO);
            
                                    @Named("RecipeIgnoreIngredientsAndBookChildRecipe")
            @Mappings({
                @Mapping(target = "book.recipes", ignore = true),
                @Mapping(target = "ingredients", ignore = true),
            })
            Recipe toEntityIgnoreIngredientsAndBookChildRecipe(RecipeDTO recipeDTO);
            
        }
    
    
    
        @Mapper(uses = {RecipeMapper.class, IngredientMapper.class})
        public interface BookMapper {
            BookMapper INSTANCE = Mappers.getMapper( BookMapper.class );
            
            @Mappings({
                @Mapping(target = "recipes", qualifiedByName = "RecipeSetIgnoreBookAndIngredientChildRecipes"),
            })
            BookDTO toDTO(Book book);
    
            @Mappings({
                @Mapping(target = "recipes", qualifiedByName = "RecipeSetIgnoreBookAndIngredientChildRecipes"),
            })
            Book toEntity(BookDTO book);
        }
    
    
    
        @Mapper(uses = {RecipeMapper.class, BookMapper.class})
        public interface IngredientMapper {
            IngredientMapper INSTANCE = Mappers.getMapper( IngredientMapper.class );
    
            // Don't forget to add the matching inverse mapping from DTO to Entity, this is basically just a copy with switch input parameter and return types
            @Named("IngredientSetIgnoreRecipes")
            IterableMapping(qualifiedByName = "IngredientIgnoreRecipes")                                // Refer to the mapping for a single object in the collection
            Set<IngredientDTO> toDTOSetIgnoreRecipes(Set<Ingredient> ingredients);
    
            // Don't forget to add the matching inverse mapping from DTO to Entity, this is basically just a copy with switch input parameter and return types
            @Named("IngredientIgnoreRecipes")
            @Mappings({
                @Mapping(target = "recipes", ignore = true),                                            // ignore the recipes property entirely
            })
            IngredientDTO toDTOIgnoreRecipes(Ingredient ingredient);
    
            @Mappings({
                @Mapping(target = "recipes", qualifiedByName = "RecipeSetIgnoreIngredientsAndBookChildRecipe")
            })
            IngredientDTO toDTO(Ingredient ingredient);
    
            @Named("IngredientSetIgnoreRecipes")
            IterableMapping(qualifiedByName = "IngredientIgnoreRecipes")                                // Refer to the mapping for a single object in the collection
            Set<Ingredient> toEntitySetIgnoreRecipes(Set<IngredientDTO> ingredientDTOs);
    
            @Named("IngredientIgnoreRecipes")
            @Mappings({
                @Mapping(target = "recipes", ignore = true),
            })
            Ingredient toEntityIgnoreRecipes(IngredientDTO ingredientDTO);
    
            @Mappings({
                @Mapping(target = "recipes", qualifiedByName = "RecipeSetIgnoreIngredientsAndBookChildRecipe")
            })
            Ingredient toEntityIgnoreRecipes(IngredientDTO ingredientDTO);
        }
    

    用法

    <ENTITY_NAME>DTO <eNTITY_NAME>DTO = <ENTITY_NAME>Mapper.INSTANCE.toDTO( <eNTITY_NAME> );`
    

    【讨论】:

    • 为映射忽略某些内容是不一样的……使用上下文的方法对其他人有效。你怎么了?
    【解决方案3】:

    至少在 mapstruct 1.3 中,您可以使用以下内容:

    该解决方案受到https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-mapping-with-cycles/src/main/java/org/mapstruct/example/mapper的广泛启发

    定义一个上下文类(受到https://github.com/mapstruct/mapstruct-examples/blob/master/mapstruct-mapping-with-cycles/src/main/java/org/mapstruct/example/mapper/CycleAvoidingMappingContext.java 的广泛启发):

    /**
     * An implementation to track cycles in graphs to be used as {@link Context} parameter.
     *
     */
    public class CycleAvoidingMappingContext {
        private Map<Object, Object> knownInstances = new IdentityHashMap<Object, Object>();
    
        /**
         * Gets an instance out of this context if it is already mapped.
         * 
         * @param source
         *        given source
         * @param targetType
         *        given target type.
         * @return Returns the resulting type.
         */
        @BeforeMapping
        public <T> T getMappedInstance(Object source, @TargetType Class<T> targetType) {
            return targetType.cast(knownInstances.get(source));
        }
    
        /**
         * Puts an instance into the cache, so that it can be remembered to avoid endless mapping.
         * 
         * @param source
         *        given source
         * @param target
         *        given target
         */
        @BeforeMapping
        public void storeMappedInstance(Object source, @MappingTarget Object target) {
            knownInstances.put( source, target );
        }
    }
    

    在使用循环引用映射类的每个映射器中,添加此org.mapstruct.Context

    /**
     * Mapper. Automatically implemented by mapstruct.
     * 
     */
    @Mapper
    public interface SomeObjWithCyclesMapper {
    
        /**
         * instance.
         */
        SomeObjWithCyclesMapper INSTANCE = Mappers.getMapper(SomeObjWithCyclesMapper.class);
    
        /**
         * Mapper method to map entity to domain. Automatically implemented by mapstruct.
         * 
         * @param entity
         *        given entity.
         * @param context
         *        context to avoid cycles.
         * @return Returns the domain object.
         */
        SomeObjWithCycles entityToDomain(SomeObjWithCyclesEntity entity, @Context CycleAvoidingMappingContext context);
    
        /**
         * Mapper method to map domain object to entity. Automatically implemented by mapstruct.
         * 
         * @param domain
         *        given domain object.
         * @param context
         *        context to avoid cycles.
         * @return Returns the entity.
         */
        SomeObjWithCyclesEntity domainToEntity(SomeObjWithCycles domain, @Context CycleAvoidingMappingContext context);
        
    }
    

    用法(2021 年 9 月 21 日添加):

    然后你可以调用mapper方法:

    SomeObjWithCyclesMapper.INSTANCE.domainToEntity(objWithCycles, new CycleAvoidingMappingContext());
    

    其中objWithCycles 是您要映射的SomeObjWithCycles 类的对象。

    【讨论】:

    • 很好的答案,办公网站示例链接:github.com/mapstruct/mapstruct-examples/tree/master/…
    • 如果getMappedInstancestoreMappedInstance 都使用相同的注解,mapstruct 的生成器如何知道何时调用?
    • 如果您为实体和 DTO 使用对象构建器,这些方法将不起作用。我已经报告了这个错误。 github.com/mapstruct/mapstruct-examples/issues/119
    • 答案不清楚。我必须如何使用它?...假设我在需要映射器的地方有服务。我必须调用 mapper.toDto(entity, context.?(?, ?))
    • 最后添加用法
    【解决方案4】:

    在 MapStruct 中还没有检测或特殊处理此类情况,但有一个功能请求:#469。如果您对如何处理周期有任何想法,请在该问题上发表评论。

    【讨论】:

    • 我希望我做到了!一个人可以做 a-la-Hibernate:使用一个包装类,当调用 getter 时,当场转换它。或者,如问题的创建者所述,使用映射来保存已转换的项目,并且当您在转换过程中发现之前已转换的对象时,请在 setter 中使用该对象,而不是转换新对象。但我真的不够专业,无法轻松提出这样的建议
    【解决方案5】:

    在此页面上很难找到答案,所以我将发布在我的案例中有效的方法以防止循环引用。

    George Siggouroglou 的回答使用以下方法运行良好:

    @Mapping(target = "primaryObject.secondaries", expression = "java(null)"),
    SecondaryObjectDto toSecondaryObjectDto(SecondaryObject source);
    

    Ivo Eersel 的回答非常完整,但我仍然设法在第一次阅读时错过了解决方案。

    所以这是我最终使用的:

    @Mapping(target = "primaryObject.secondaries", ignore = true)
    SecondaryObjectDto toSecondaryObjectDto(SecondaryObject source);
    

    【讨论】:

    • 这不是映射primaryObject.secondaries ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多