如何在父对象上使用mapstruct来检测正确的子映射器?

时间:2019-03-20 13:12:17

标签: java mapstruct

mapstruct是否允许从父对象中检测正确的子映射器?

我们有多个扩展父类的类,我们想要一种自动找到正确的映射器的方法。

我所涉及的解决方案涉及映射器类的映射,并在检查对象类或类型时加载正确的映射器。 另一个解决方案是使用复杂的开关盒,或者使用每个可能的子类的实例。

模型示例:

public class ParentClass{
String getType();
}

public class ChildClass1 extends ParentClass{

}

public class ChildClass2 extends ParentClass {
}

此dto模型:

public class ParentClassDto{
String getType();
}

public class ChildClass1Dto extends ParentClassDto{

}

public class ChildClass2Dto extends ParentClassDto {
}

一切都是一对一的(ChildClass1->带有C​​hildClass1Mapper的ChildClass1Dto或ChildClass2->带有C​​hildClass2Mapper的ChildClass2Dto)

我们当前的解决方案涉及一个带有映射器的地图,如下所示:

@Mapper
public interface ParentClassMapper{
    ParentClassDto convertToDto(ParentClass p);
    ParentClass convertDTOToModel(ParentClassDto dto);
}


@Mapper
public interface ChildClass1Mapper implements ParentClassMapper

找到合适的地图:

public class MapperFinder{

    static Map<String, ParentClassMapper> map;

    static {
        map = new HashMap<>();
        map.put("ParentClassType", ParentClassMapper.class);
        map.put("ChildClass1Type", ChildClass1Mapper.class);
        map.put("ChildClass2Type", ChildClass2Mapper.class);
    }

    public ParentClassDto mapModelToDTO(ParentClass p){
        Class mapperClass = map.get(p.getType);
        MyMapper mapper = Mappers.getMapper( mapperClass );
        return mapper.convertToDto(p);
    }


    public ParentClass mapDTOToModel(ParentClassDto dto){
        Class mapperClass = map.get(dto.getType);
        MyMapper mapper = Mappers.getMapper( mapperClass );
        return mapper.convertDTOToModel(dto);
    }
}

用法将在服务中

@Autowired
MapperFinder mapperFinder;

public void save (ParentClass pc){
    (pc is a instance of child ChildClass1)
    ... 
    ParentClassDto dto = mapperFinder.mapModelToDTO(pc);
    repo.save(dto);
    ...
}

还有另一种方法吗?

1 个答案:

答案 0 :(得分:1)

在示例存储库中查看this示例(仍为PR)。它提出了一个标准的映射器接口和一个存储库功能(或多或少)来实现您想要的。

相关问题