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

时间:2017-12-20 10:39:43

标签: java mapstruct

我正在尝试使用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;

}

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

2 个答案:

答案 0 :(得分:3)

为避免嵌套字段的无限交叉设置,您应限制此依赖性,例如在第二个嵌套级别,即您的根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 

}

答案 1 :(得分:1)

这应该是直截了当的,在你的情况下没有任何挑战:

@Mapper
public interface EmailInfoMapper {

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

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

您应该在问题中包含您的映射器,以及您遇到的问题。