欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot项目中DO、BO、DTO之间相互传输数据的工具类

程序员文章站 2022-06-22 20:13:53
在springboot项目单靠实体类不能够满足前后端传输模型的需求,所以我们又建了DO、BO、DTO等模型来方便数据的传输,但是他们之间往往又会进行转换,下面是一个任意两个模型相互转换的工具类:public class MyBeanUtils { public static String[] getNullPropertyNames(Object source) { final BeanWrappe...

       在springboot项目单靠实体类不能够满足前后端传输模型的需求,所以我们又建了DO、BO、DTO等模型来方便数据的传输,但是他们之间往往又会进行转换,下面是一个任意两个模型相互转换的工具类:

public class MyBeanUtils
{
    public static String[] getNullPropertyNames(Object source)
    {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set < String > emptyNames = new HashSet < > ();
        for(PropertyDescriptor pd: pds)
        {
            Object srcValue = src.getPropertyValue(pd.getName());
            if(srcValue == null)
            {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
    public static void copyNotNullProperties(Object source, Object target)
    {
        String[] ignoreProperties = getNullPropertyNames(source);
        BeanUtils.copyProperties(source, target, ignoreProperties);
    }
}

调用:

MyBeanUtils.copyNotNullProperties(xxxDto,xxxDo); 

MyBeanUtils.copyNotNullProperties(xxxDo,xxxBo);

相关标签: springboot