项目场景:
源和目标实体类中的客户ID字段不对应,在使用Hutool
的BeanUtil
拷贝时字段为空
问题描述
源实体类属性:
/**
* 客户ID
*/
private String customerId;
目标实体类属性
/**
* 客户ID
*/
private String customId;
解决方法:
有两种解决办法,觉得哪个方便用哪个。
方法(一)、在源实体类不对应的字段上加@Alias
注解,使用别名映射目标类的属性名
@Alias("customId")
private String customerId;
方法(二)、使用BeanUtil中带CopyOptions
参数的方法,设置字段映射Map
这里用图中第6个方法拷贝集合做示例,如果是拷贝对象,用第三个即可.
Map<String, String> mapping = new HashMap<>(1);
// key 为源字段,value为目标字段
mapping.put("customerId", "customId");
BeanUtil.copyToList(源数组,目标实体类.class, new CopyOptions().setFieldMapping(mapping))