java – Dozer双向映射(String,String)与自定义转换器不可能?
作者:互联网
我有一个自定义转换器的推土机映射:
<mapping>
<class-a>com.xyz.Customer</class-a>
<class-b>com.xyz.CustomerDAO</class-b>
<field custom-converter="com.xyz.DozerEmptyString2NullConverter">
<a>customerName</a>
<b>customerName</b>
</field>
</mapping>
和转换器:
public class DozerEmptyString2NullConverter extends DozerConverter<String, String> {
public DozerEmptyString2NullConverter() {
super(String.class, String.class);
}
public String convertFrom(String source, String destination) {
String ret = null;
if (source != null) {
if (!source.equals(""))
{
ret = StringFormatter.wildcard(source);
}
}
return ret;
}
public String convertTo(String source, String destination) {
return source;
}
}
当我向一个方向调用mapper时(Customer – > CustomerDAO),调用方法’convertTo’.
由于Dozer能够处理双向映射,我希望,只要我在相反的方向上调用mapper,就会调用’convertFrom’方法.
但是从不调用convertTo方法.
我怀疑问题是,两种类型都是字符串 – 但我怎样才能使这个工作?
作为一种解决方法,我创建了两个单向映射,这是标准解决方案,还是行为是一个bug?
解决方法:
是的,问题是您的源和目标类是相同的.这是Dozer source for DozerConverter:
public Object convert(Object existingDestinationFieldValue, Object sourceFieldValue, Class<?> destinationClass, Class<?> sourceClass) {
Class<?> wrappedDestinationClass = ClassUtils.primitiveToWrapper(destinationClass);
Class<?> wrappedSourceClass = ClassUtils.primitiveToWrapper(sourceClass);
if (prototypeA.equals(wrappedDestinationClass)) {
return convertFrom((B) sourceFieldValue, (A) existingDestinationFieldValue);
} else if (prototypeB.equals(wrappedDestinationClass)) {
return convertTo((A) sourceFieldValue, (B) existingDestinationFieldValue);
} else if (prototypeA.equals(wrappedSourceClass)) {
return convertTo((A) sourceFieldValue, (B) existingDestinationFieldValue);
} else if (prototypeB.equals(wrappedSourceClass)) {
return convertFrom((B) sourceFieldValue, (A) existingDestinationFieldValue);
} else if (prototypeA.isAssignableFrom(wrappedDestinationClass)) {
return convertFrom((B) sourceFieldValue, (A) existingDestinationFieldValue);
} else if (prototypeB.isAssignableFrom(wrappedDestinationClass)) {
return convertTo((A) sourceFieldValue, (B) existingDestinationFieldValue);
} else if (prototypeA.isAssignableFrom(wrappedSourceClass)) {
return convertTo((A) sourceFieldValue, (B) existingDestinationFieldValue);
} else if (prototypeB.isAssignableFrom(wrappedSourceClass)) {
return convertFrom((B) sourceFieldValue, (A) existingDestinationFieldValue);
} else {
throw new MappingException("Destination Type (" + wrappedDestinationClass.getName()
+ ") is not accepted by this Custom Converter ("
+ this.getClass().getName() + ")!");
}
}
不要使用convertFrom和convertTo方法(它们是新API的一部分),而是以原始方式执行,必须实现CustomConverter.convert,如tutorial所示.
标签:java,mapping,dozer 来源: https://codeday.me/bug/20190704/1382094.html