简体   繁体   English

mapstruct将实体OneToMany映射到DTO并反向

[英]mapstruct mapping Entity OneToMany to DTO and reverse

I'm trying to use a mapstruct and I need to mapping Entity with a sub Entity list, I have relationship oneToMany and manyToOne and I need to mapping in both cases: 我试图用一个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;

}

mapping to: 映射到:

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

}

How to do it in the best way ? 如何以最佳方式做到这一点?

To avoid infinite cross setting of nested fields you should limit this dependency, for example on the second nested level, ie your root EmailDTO will have one nested DeliveredEmailInfoDTO object (many-to-one relationship), while your root DeliveredEmailInfoDTO will have the list of nested EmailDTO objects (one-to-many relationship) and nothing on the next nesting level: 为避免嵌套字段的无限交叉设置,您应限制此依赖性,例如在第二个嵌套级别,即您的根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 

}

(Also see other answer) (另请参阅其他答案)

It should be straightforward, there is nothing challenging in your case: 它应该很简单,在您的情况下没有挑战:

@Mapper
public interface EmailInfoMapper {

    EmailDTO entityToDTO(EmailEntity duration);
    EmailEntity dtoToEntity(EmailDTO price);

    DeliveredEmailInfoDTO entityToDTO(DeliveredEmailInfoEntity duration);
    DeliveredEmailInfoEntity dtoToEntity(DeliveredEmailInfoDTO price);
}

You should include your mapper in your question and what the problem you have with it. 您应该在问题中包括映射器,以及问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM