Mapstruct双向映射

时间:2020-01-24 11:04:18

标签: java mapstruct

我有以下示例,其中我有一个单独的域层和一个单独的持久层。我正在使用Mapstruct进行映射,并且由于始终在->无限循环方案中调用双向引用,因此在从域到实体或从实体到域的映射时会得到StackOverflow。在这种情况下如何使用Mapstruct?

class User {
  private UserProfile userProfile;
}

class UserProfile {
 private User user;
}

@Entity
class UserEntity {
  @OneToOne
  @PrimaryKeyJoinColumn
  private UserProfileEntity userProfile;
}

@Entity
class UserProfileEntity {
  @OneToOne(mappedBy = "userProfile")
  private UserEntity userEntity;
}

用于映射的类非常基础

@Mapper
interface UserMapper {

UserEntity mapToEntity(User user);

User mapToDomain(UserEntity userEntity);
}

1 个答案:

答案 0 :(得分:5)

查看Mapstruct mapping with cycles示例。

in the documentation for Context annotation也展示了您的问题的解决方案。

示例

完整的示例:https://github.com/jannis-baratheon/stackoverflow--mapstruct-mapping-graph-with-cycles

参考

映射器:

groupBy

其中BundleConfig.cs跟踪已映射的对象并重用它们以避免堆栈溢出:

defaultScssBundle.Builder = nullBuilder;
defaultScssBundle.Transforms.Add(styleTransformer);
defaultScssBundle.Transforms.Add(new CssMinify());

映射器用法(映射单个对象):

@Mapper
public interface UserMapper {

    @Mapping(target = "userProfileEntity", source = "userProfile")
    UserEntity mapToEntity(User user,
                           @Context CycleAvoidingMappingContext cycleAvoidingMappingContext);

    @InheritInverseConfiguration
    User mapToDomain(UserEntity userEntity,
                     @Context CycleAvoidingMappingContext cycleAvoidingMappingContext);

    @Mapping(target = "userEntity", source = "user")
    UserProfileEntity mapToEntity(UserProfile userProfile,
                                  @Context CycleAvoidingMappingContext cycleAvoidingMappingContext);

    @InheritInverseConfiguration
    UserProfile mapToDomain(UserProfileEntity userProfileEntity,
                            @Context CycleAvoidingMappingContext cycleAvoidingMappingContext);
}

您还可以在映射器上添加默认方法:

CycleAvoidingMappingContext
相关问题