實體與Dto自動賦值
在開發的過程當中,實體之間相互賦值是很正常的事,可是咱們通常的方法都經過set和get方法來進行的,若是要賦值的字段少那還行,可是須要賦值的字段超過10個,那就是個災難,你會看到整屏代碼中全是set和get方法。前端
- 兩個實體屬性字段幾乎徹底相同
- 兩個字體有部分字段相同
- 源實體只有部分字段賦值,目標實體有完整的值
第一種狀況
對於第1點來講,咱們用到最多的就是entity和dto之間的轉換了,這個咱們可使用Spring的工具類BeanUtils來解決,這裏要注意的一點是,==第一個參數是源,第二個參數是目標==。java
import org.springframework.beans.BeanUtils; BeanUtils.copyProperties(origin, target);
第二種狀況
可是對於第2點來講,就沒有那麼簡單了,再使用BeanUtils已經不能知足咱們的須要了。 咱們可使用jackson的ObjectMapperspring
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的過濾參數:json
/* 經過該方法對mapper對象進行設置,全部序列化的對象都將按改規則進行系列化 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); }
集合轉集合
String requestData="[]"; List<ProductDetail> list = objectMapper.readValue(requestData, new TypeReference<List<ProductDetail>>() { }); repository.saveAll(list);
經過objectMapper的使用,確實讓咱們少寫不少重複的代碼。app