我正在使用Dozer(5.3.2)从源Person对象映射到目标Person对象。 Person的超类的默认构造函数在对象上设置UUID。因此,当我将源映射到新Person时,新Person上的UUID已经设置,因此不会从源对象复制。在代码中(完整代码向下):
DozerBeanMapper MAPPER = // ... see code further down;
Person source = new Person();
Person target = new Person();
MAPPER.map(source, target);
我想要的是:在调用MAPPER.map(...)之后,我希望target.getUuid()等于source.getUuid()。截至目前,它们是不同的(因为它们在超级构造函数中设置为UUID.randomUUID,见下文)。
我可以通过设置
来解决这个问题target.setUuid(null);
在调用MAPPER.MAP(...)之前,但这不是我想要的,因为这是对更复杂问题的简化。有没有办法配置Dozer或自定义类,以便映射器设置目标对象中的值,即使目标对象中的值不为空?
我的代码如下:
public abstract class AbstractEntity
{
private long uuid;
public AbstractEntity() {
this(UUID.randomUUID());
}
public AbstractEntity(long uuid) {
this.uuid = uuid;
}
public UUID getUuid()
{
return this.uuid;
}
public void setUuid(final UUID uuid)
{
this.uuid = uuid;
}
}
public class Person extends AbstractEntity
{
// Getters and setters...
}
以下是创建和执行推土机映射器的代码:
DozerBeanMapper MAPPER = new DozerBeanMapper();
BeanMappingBuilder builder = new BeanMappingBuilder() {
protected void configure() {
mapping(UUID.class, UUID.class, TypeMappingOptions.oneWay(), TypeMappingOptions.mapNull(true),
TypeMappingOptions.beanFactory(UuidBeanFactory.class.getName()));
}
};
MAPPER.addMapping(builder);
Person source = new Person();
Person target = new Person();
MAPPER.map(source, target);
UUIDBeanFactory的代码 - 我正在使用它,因为UUID没有空的构造函数,这会使Dozer抛出异常。
public class UuidBeanFactory implements BeanFactory
{
@Override
public Object createBean(Object sourceObject, Class<?> aClass, String s)
{
if (sourceObject == null)
{
return null;
}
UUID source = (UUID) sourceObject;
UUID target = new UUID(source.getMostSignificantBits(), source.getLeastSignificantBits());
return target;
}
}