在開發(fā)的過程中张弛,實體之間相互賦值是很正常的事,但是我們一般的方法都通過set和get方法來進行的酪劫,如果要賦值的字段少那還行吞鸭,但是需要賦值的字段超過10個,那就是個災難覆糟,你會看到整屏代碼中全是set和get方法刻剥。
兩個entity之間賦值,主要有以下三種情況:
1搪桂、兩個實體屬性字段幾乎完全相同
2透敌、兩個字體有部分字段相同
3盯滚、源實體只有部分字段賦值踢械,目標實體有完整的值
第一種情況
對于第1點來說,我們用到最多的就是entity和dto之間的轉換了魄藕,這個我們可以使用Spring的工具類BeanUtils來解決内列,這里要注意的一點是,==第一個參數是源背率,第二個參數是目標==话瞧。
import org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(origin, target);
第二種情況
但是對于第2點來說嫩与,就沒有那么簡單了,再使用BeanUtils已經不能滿足我們的需要了交排。
我們可以使用jackson的ObjectMapper
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.jd.fastjson.JSON;
ObjectMapper objectMapper = new ObjectMapper();
//配置該objectMapper在反序列化時划滋,忽略目標對象沒有的屬性。凡是使用該objectMapper反序列化時埃篓,都會擁有該特性处坪。
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//讀入需要更新的目標實體
ObjectReader objectReader = objectMapper.readerForUpdating(target);
//將源實體的值賦值到目標實體上
objectReader.readValue(JSON.toJSONString(source));
我們總結一下objectMapper的過濾參數:
/*
通過該方法對mapper對象進行設置,所有序列化的對象都將按改規(guī)則進行系列化
Include.Include.ALWAYS 默認
Include.NON_DEFAULT 屬性為默認值不序列化
Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化
Include.NON_NULL 屬性為NULL 不序列化
*/
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
String outJson = objectMapper.writeValueAsString(productDetail);
//上面代碼里架专,outJson的值將會過濾掉只有默認值的屬性
第三種情況
本情況主要對于從dto到entity轉換過程中出現 同窘,比如一個put操作,前端可能只修改某幾個屬性部脚,而在后端處理時也只希望處理這幾個被賦值的屬性想邦,這時我們使用下面的方法:
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public HttpEntity update(@PathVariable int id, @RequestBody ProductDetail productDetail)
throws IOException {
ProductDetail existing = repository.findById(id).get();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
String outJson = objectMapper.writeValueAsString(productDetail);
ObjectReader objectReader = objectMapper.readerForUpdating(existing);
objectReader.readValue(outJson);
repository.save(existing);
return new ResponseEntity<>(existing, HttpStatus.ACCEPTED);
}
OK,就這么多