我正在尝试使用mapstruct,我需要将Entity
映射到子Entity
列表,我有oneToMany
和manyToOne
的关系,我需要在两种情况下进行映射:
@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;
}
如何以最好的方式做到这一点?
答案 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);
}
您应该在问题中包含您的映射器,以及您遇到的问题。