这真的取决于您使用的是哪个版本的 MapStruct。如果您使用的是 1.2.0.Beta 或更高版本,您可以在EntityMapper界面上定义嵌套属性:
@Mapper
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
@Mapping(target = "anotherEntity.propE", source = "anotherEntityDTO.propD")
Entity map(EntityDDTO dto);
}
另一种选择(如果您使用的版本低于 1.2.0.Beta,则必须这样做)是添加一个新的方法EntityMapper:
@Mapper
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
Entity map(EntityDDTO dto);
@Mapping(target = "propE", source = "propD")
AnotherEntity map(AnotherEntityDTO);
}
AnotherEntityMapper或者您可以为AnotherEntity和使用定义一个新的映射器@Mapper(uses = {AnotherEntityMapper.class}):
@Mapper
public interface AnotherEntityMapper {
@Mapping(target = "propE", source = "propD")
AnotherEntity map(AnotherEntityDTO);
}
@Mapper(uses = {AnotherEntityMapper.class}
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
Entity map(EntityDDTO dto);
}
这实际上取决于您的用例。如果您需要在其他地方之间进行映射AnotherEntity,AnotherEntityDTO我建议您使用新界面,以便您可以在需要的地方重用它