mapstruct mapping Entity OneToMany to DTO and reverse

我的未来我决定 提交于 2020-04-16 04:41:29

问题


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:

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


回答1:


(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.




回答2:


To avoid infinite cross setting of nested fields you should limit this dependency, for example on the second nested level, i.e. 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:

@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 

}


来源:https://stackoverflow.com/questions/47904111/mapstruct-mapping-entity-onetomany-to-dto-and-reverse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!