Orika:如何使用嵌套映射器进行映射

Orika: How to map using a nested mapper

考虑以下情况:

public class A {

    private ClassInA classInA;

    public ClassInA getClassInA() {
        return classInA;
    }

    public void setClassInA(ClassInA classInA) {
        this.classInA = classInA;
    }

}

public class B {

    private ClassInB classInB;

    public ClassInB getClassInB() {
        return classInB;
    }

    public void setClassInB(ClassInB classInB) {
        this.classInB = classInB;
    }

}

public class ClassInA {

    private String myString;

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

}

public class ClassInB {

    private String myString;

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

}

现在我想使用 orika 将 A 映射到 B。我需要一个转换器来这样做。喜欢:

public class MyMapper {

    @Override
    protected void configure(MapperFactory factory) {
        ConverterFactory converterFactory = factory.getConverterFactory();
        converterFactory.registerConverter(new MyConverter());

        factory.classMap(A.class, B.class) //
                .field("classInA", "classInB") //
                .register();
    }
}

public class MyConverter extends CustomConverter<ClassInA, ClassInB> {

    @Override
    public ClassInB convert(ClassInA source, Type<? extends ClassInB> destinationType) {
        ClassInB classInB = new ClassInB();
        classInB.setMyString(source.getMyString());
        return classInB;
    }

}

尽管 ClassInAClassInB 的映射器会更好。喜欢:

public class MyMapper extends ConfigurableMapper {

    @Override
    protected void configure(MapperFactory factory) {
        factory.classMap(ClassInA.class, ClassInB.class) //
                .byDefault
                .register();
    }
}

遗憾的是,我不知道如何在 MyMapper 中注册映射器。没有什么比 converterFactory.registerMapper(new MyMapper());。我能做到这一点的唯一方法是通过

.customize(
    return new CustomMapper<LoanContractRequestValue, LoanContrReqERPCrteReqLoanContr>() {
        @Override
        public void mapAtoB(A source, B destination, MappingContext context) {
            destination.setMyString(source.getMyString());
        }
    };
)

但这真的是要走的路吗?

你可以在同一个mapperFactory中注册多个classMaps,Orika会根据class/type知道使用哪个。

public class MyMapper extends ConfigurableMapper {
    @Override
    protected void configure(MapperFactory factory) {
        factory.classMap(A.class, B.class)
                .field("classInA", "classInB")
                .register();

        factory.classMap(ClassInA.class, ClassInB.class)
                .byDefault
                .register();
    }
}