背景:最近工作上遇到一些需要对象Dto转为Po的场景,分享一下。
OrderPo target = 获取的目标对象;
OrderDto source = 获取的原始对象;
Merge.withConfiguration(new MergeConfiguration<OrderDto, OrderPo>()
//原始对象的ZonedDateTime转换为String,也可以写其他业务逻辑,如转为时间戳
.custom(ZonedDateTime.class, String.class, DateUtil::parseISODateTime)
//Type::of方法操作原始对象的属性值转为String
.custom(Type.class, String.class, Type::of)
/**
* 根据原始对象的address.phone属性,写需要的业务逻辑,fieldName(属性名), source
* (源对象), target(目标对象), oldValue(原始对象此属性值), newValue(目标对
* 象此属性值)
*/
.notifyUpdate("address.phone", ((fieldName, source, target, oldValue, newValue) -> changedFlag(target, oldValue)))
//字段值不同执行逻辑
.notifyUpdate("status", (fieldName, source, target, from, to) -> {
//写对应的业务逻辑
Boolean result = tryToSyncUpdateId(source, target);
target.setUpdateDate(ZonedDateTime.now());
if (result) {
try {
toSync(false, target, source);
} catch (InternalServerException e) {
target.setOrderStatus(null);
throw e;
}
}
kafkaProducerService.sendKafka(new KafkaMessageDto(topic, source));
})
).merge(source, target);