【发布时间】:2018-10-05 14:29:42
【问题描述】:
我有一个父级,其中有一组要映射的子级。
Parent -> Collection<Child> children
ParentDTO -> Collection<ChildDTO> childDTOs
从 DTO 到域我想要一个数据库查找调用:我有一个服务方法可以在它的 id 上查找一个孩子:
Child getChild(Long id)
现在在父 dtoToDomain(parentDTO) 中,我希望 mapstruct 对集合中的每个项目进行查找。
此方案适用于单occ,mapstruct可以在服务中找到getChild并编写查找动作:
@Mapper(uses = ChildService.class)
public interface ParentMapper {
@Mapping(source="child.id", target="child")
Parent dtoToDomain(ParentDTO parentDTO);
}
但是,对于一个集合,我必须为集合映射指定一个特定的方法,但是我在@Mapping 中放了什么?像这样?
@Mapping(source="child.id", target="child")
Collection<Child> dtoToDomain(Collection<ChildDTO> children)
我看不出如何编写默认实现,因为我需要由实现自动装配的服务。
我可以想象这个解决方案:一个子映射器,在其中我使用如下查找覆盖 Dto 到 Domain 方法:
@Mapper(uses = ChildMapper.class)
public interface ParentMapper {
Parent dtoToDomain(ParentDTO parentDTO);
}
@Mapper(uses = ChildService.class)
public interface ChildMapper {
@Mapping(source="id", target="")
Child dtoToDomain(ChildDTO child);
}
但是在 mapstruct 中 target 是强制性的。也许我可以以某种方式将整个对象指定为目标?
【问题讨论】:
标签: collections nested mapping mapstruct