gpt4 book ai didi

java - mapstruct 映射实体 OneToMany 到 DTO 和反向

转载 作者:行者123 更新时间:2023-11-29 08:31:23 41 4
gpt4 key购买 nike

我正在尝试使用 mapstruct我需要将 Entity 映射到子 Entity 列表,我有 oneToManymanyToOne 关系,我需要两种情况下的映射:

@Data
@Entity
public class EmailEntity {

private int id;

... // some fields

@ManyToOne
private DeliveredEmailInfoEntity deliveredEmailInfo;

}

.

@Data
@Entity
public class DeliveredEmailInfoEntity {

private int id;

... // some fields

@OneToMany
private List<EmailEntity> emails;

}

映射到:

@Data
public class EmailDTO {

private int id;

... // some fields

private DeliveredEmailInfoDTO deliveredEmailInfo;

}

.

@Data
public class DeliveredEmailInfoDTO {

private int id;

... // some fields

private List<EmailDTO> emails;

}

如何以最好的方式做到这一点?

最佳答案

为了避免嵌套字段的无限交叉设置,您应该限制这种依赖性,例如在第二个嵌套级别上,即您的根 EmailDTO 将有一个嵌套的 DeliveredEmailInfoDTO 对象(多对一关系),而您的根 DeliveredEmailInfoDTO 将具有嵌套的 EmailDTO 对象列表(一对多关系),而在下一个嵌套级别上没有任何内容:

@Mapper(uses = DeliveredEmailInfoMapper.class)
public interface EmailMapper {

@Mapping(target = "deliveredEmailInfo.emails", ignore = true)
EmailDTO toDTO(EmailEntity entity);

// other methods omitted

@Named("emailDTOList")
default List<EmailDTO> toEmailDTOList(List<EmailEntity> source) {
return source
.stream()
.map(this::toDTO)
.peek(dto -> dto.setDeliveredEmailInfo(null))
.collect(Collectors.toList());
}
}

@Mapper(uses = EmailMapper.class)
public interface DeliveredEmailInfoMapper {

@Mapping(target = "emails", source = "emails", qualifiedByName = "emailDTOList")
DeliveredEmailInfoDTO toDTO(DeliveredEmailInfoEntity entity);

// other methods omitted

}

关于java - mapstruct 映射实体 OneToMany 到 DTO 和反向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904111/

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