gpt4 book ai didi

java - Mapstruct 双向映射

转载 作者:行者123 更新时间:2023-12-01 19:30:27 30 4
gpt4 key购买 nike

我有以下示例,其中我有一个单独的域层和一个单独的持久层。我使用 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);
}

最佳答案

查看 Mapstruct mapping with cycles示例。

还演示了您的问题的解决方案 in the documentation for Context annotation .

示例

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

引用

映射器:

@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跟踪已映射的对象并重用它们以避免堆栈溢出:

public class CycleAvoidingMappingContext {
private final Map<Object, Object> knownInstances = new IdentityHashMap<>();

@BeforeMapping
public <T> T getMappedInstance(Object source,
@TargetType Class<T> targetType) {
return targetType.cast(knownInstances.get(source));
}

@BeforeMapping
public void storeMappedInstance(Object source,
@MappingTarget Object target) {
knownInstances.put(source, target);
}
}

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

UserEntity mappedUserEntity = mapper.mapToEntity(user, new CycleAvoidingMappingContext());

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

@Mapper
public interface UserMapper {

// (...)

default UserEntity mapToEntity(User user) {
return mapToEntity(user, new CycleAvoidingMappingContext());
}

// (...)
}

关于java - Mapstruct 双向映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895166/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com