Orika - 如何映射继承和展平?

时间:2017-08-09 08:42:44

标签: orika

我一直在努力完成一项任务,如何告诉Orika映射一个扁平化为DTO的继承结构,以便它可以正确地解决重建对象时的实现。下面是一个包含许多嵌套对象的简单结构示例:

abstract class Document {
  // common values
}

class LegalDocument extends Document {
  // complex object with many nested objects
}

class PersonalDocument extends Document {
  // complex object with many nested objects
}

让我们说我有理由让上面的结构弄平对象:

class FlattenedDocument {
  private String documentType = "LEGAL"; // "LEGAL" or "PERSONAL"

  // flattened properties of Document and both its subclasses
}

我可以通过CustomMapper<Document, FlattenedDocument>告诉Orika根据输入文档的实际类型(类)正确映射属性documentType,但是我不知道知道该怎么做才是相反的情况。我需要告诉Orika,当它从FlattenedDocument转换为abstract Document的一个实现时,是否应该通过documentType属性的值创建前者或后者。我可以通过CustomConverterObjectFactory执行此操作,但在这两种情况下,我都会失去byDefault()的好处。

有没有办法如何将标准ClassMap与byDefault()选项

一起使用
factory.classMap(Document.class, FlattenedDocument.class).byDefault().register();

但有可能告诉Orika它应该根据documentType字段的值重新实例化对象吗?

感谢。

1 个答案:

答案 0 :(得分:0)

您可以创建 CustomConverter ,根据您的字段决定类型:

public class ShapeReverseConverter extends CustomConverter<ShapeDTO, Shape> {

    @Override
    public Shape convert(ShapeDTO source, Type<? extends Shape> destinationType, MappingContext mappingContext) {
        if (Circle.class.getSimpleName().equals(source.type)) {
            return mapperFacade.map(source, Circle.class);
        } else {
            return mapperFacade.map(source, Rectangle.class);
        }
    }

}

配置中,您可以映射设置类型:

DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.classMap(Shape.class, ShapeDTO.class).byDefault()
            .field("class.simpleName", "type")
            .register();
mapperFactory.getConverterFactory().registerConverter(new ShapeReverseConverter());
相关问题