考虑以下情况:
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;
}
}
虽然ClassInA
到ClassInB
的映射器会更好。像:
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());
}
};
)
但这真的是一种方法吗?
答案 0 :(得分:1)
您可以在同一个mapperFactory中注册多个classMaps,Orika将根据类/类型知道要使用哪个类。
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();
}
}