在学习ERP对接电商平台的相关技术时,看到了这一段代码,敏感内容已隐去。
使用了BeanUtils.copyProperties(a,b)方法,查询后特地记录一下该方法的用法。
其中allList是一组已经排除了为空为零对象的数组,储存了库存信息。这里执行一个对原数据库的update/insert操作。
import org.springframework.beans.BeanUtils;
。
。
。
Integer insertNum=0;
Integer updateNum=0;
for (InventoryModel i:allList){
//通过设计好的select语句,调出原数据库的数据并赋值给空的对象entity
InventoryEntity entity=InventoryMapper.select(i.getWarehouseCode(),i.getInventoryCode());
//如果entity不为空,那么就是旧的数据,执行更新操作,否则执行插入操作
if(entity!=null){
updateNum+=1;
//更新操作,把遍历取出的值覆盖到原值上去,也就是i覆盖entity
//这个传值操作主要看导入的包,是org.springframework.beans.BeanUtils;
//所以是前拷贝到后,在这里即把 i 的值拷贝到 entity
BeanUtils.copyProperties(i,entity);
InventoryMapper.update(entity);
}else{
//插入操作,把一个空的新对象赋值给entity,然后把i的值传递到entity
//最终执行insert操作,参数为entity
insertNum+=1;
entity=new InventoryEntity();
BeanUtils.copyProperties(i,entity);
InventoryMapper.insert(entity);
}
}
通过代码我们可以确认在这里是是把前值赋给后值,但是有的资料又说把后值赋给前值。
比如:
https://www.cnblogs.com/baizhanshi/p/6096810.html
经过查阅,总结如下:
BeanUtils是org.springframework.beans.BeanUtils, a拷贝到b
import org.springframework.beans.BeanUtils
public static void copyProperties(Object source, Object target) throws BeansException{
//source 源文件,target 目标文件
copyProperties(source, target, null, (String[])null);
}
BeanUtils是org.apache.commons.beanutils.BeanUtils,b拷贝到a
import org.apache.commons.beanutils.BeanUtils
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException{
//dest(英译:“蒸馏”,可理解为空白文件,目标文件),original原始的,源文件
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}
所以导入不同的包,该方法的赋值顺序是不一样的,在使用时,要注意到这一点
快捷导包时两个包都会弹出供选.jpg注意不能选错了。
参考博客:
从后往前赋值的情况:
https://www.cnblogs.com/baizhanshi/p/6096810.html
两者的用法和区别:
https://www.cnblogs.com/SimonHu1993/p/7356058.html
使用时应该注意的问题:
https://blog.csdn.net/qq_21033663/article/details/71794648
网友评论