前言:
關聯博客:
【Java】【3】BeanUtils.copyProperties();將一個實體類的值復制到另外一個實體類 - 花生喂龍 - 博客園
https://www.cnblogs.com/huashengweilong/p/10690509.html
關聯博客里的是最簡單的兩個實體類賦值的情況,將oldEntity的值,賦給newEntity。而項目中有時的要求是,newEntity里的對應字段有值,就用newEntity里的;沒有值,才將oldEntity的值賦給newEntity。
正文:
用法:
BeanUtil.copyProperties(oldObject, newObject, true, CopyOptions.create().setXXXX(true))
參數:
editable:限制的類或接口,必須為目標對象的實現接口或父類,用於限制拷貝的屬性,例如一個類我只想復制其父類的一些屬性,就可以將editable設置為父類。
ignoreNullValue:是否忽略空值,當源對象的值為null時,true: 忽略而不注入此值,false: 注入null
ignoreProperties:忽略的屬性列表,設置一個屬性列表,不拷貝這些屬性值
ignoreError:是否忽略字段注入錯誤
可以通過CopyOptions.create()方法創建一個默認的配置項,通過setXXX方法設置每個配置項
當前需求的寫法:
BeanUtil.copyProperties(oldDetail.get(), userDetail, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
pom.xml
//這是別人寫的jar包,他的文檔:http://hutool.mydoc.io/#text_319433 <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.1.14</version> </dependency>
代碼
public Entity test(Entity inputEntity){ Entity newEntity = new Entity(); Entity oldEntity = this.dao...; //從數據庫獲取 if (oldDetail.isPresent()) { BeanUtil.copyProperties(oldEntity.get(), inputEntity, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)); } BeanUtil.copyProperties(inputEntity, newEntity); return newEntity; }
參考博客:
BeanUtils.copyProperties忽略null值/只拷貝非null屬性 - ★【World Of Moshow 鄭鍇】★ - CSDN博客
https://blog.csdn.net/moshowgame/article/details/82826535