关于两个实体类之间相同字段的赋值

发布时间 2023-11-14 16:42:27作者: xiaobaibao

1.可以使用以下方法:

BeanUtils.copyProperties(one,two)

2.相关依赖:

<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>number</version> <!-- 替换为正确的版本号 -->可以是:1.9.0
</dependency>

3.解释:

1)两个实体类里面如果有字段不一样,那就不会被复制过去,因为BeanUtils.copyProperties() 是根据属性名字匹配进行字段复制的,如果两个实体类里面有相同的字段名字,就会复制过去,但如果有相同的字段名字和不同的类型,可能会出现类型转换异常等问题。

2)1)的解决方式:使用自定义转换器转换字段的数据类型,如下:

public class Main {
    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setBirthday(new Date());

        Customer customer = new Customer();

        // 自定义属性转换器,将 java.util.Date 类型的 birthday 转换成 java.time.LocalDate 类型
        Converter converter = new Converter() {
            @Override
            public Object convert(Class type, Object value) {
                if (type == LocalDate.class && value instanceof Date) {
                    return ((Date) value).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                }
                return value;
            }
        };

        // 将 person 的值赋给 customer,使用带有属性转换器的 BeanUtils.copyProperties()
        BeanUtils.copyProperties(customer, person, converter);
    }
}