實體類轉換DTO的方式

背景:在對外傳輸數據展示過程中,爲了避免model層直接對外暴露,我們會多加一個對應的DTO保理想要傳輸的數據即可,隱藏model層。

應對:
1.第一種,如果是實體類字段類型都一樣,大部分會採用bean拷貝的方式,BeanUtils.copyProperties(obj,obj),單個對象的轉換還好,但是List對象就要循環來轉換。

2.第二種,要是遇到駝峯類型字段與下劃線字段的對象進行轉換也是頭疼,由於可能接口跟實體類不是一波人寫的,在一致性上沒用做統一的規範,導致model和DTO的字段類型還不一樣。這種fastJson有對應的轉換

/**
     * 將對象的大寫轉換爲下劃線加小寫,例如:userName-->user_name
     *
     * tar 目標對象
     * to 轉換對象
     * @return
     * @throws Exception
     */
    public static Object toUnderline(Object tar,Object to) throws Exception {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String json=JSON.toJSONString(tar,config);
        return JSON.parseObject(json, to.getClass());
    }

SnakeCase 就是一種轉換下劃線的策略,當然也是可以互轉的,只要修改策略的枚舉值爲CamelCase,就轉爲駝峯。

3.第三種,爲了保持我們提供的接口代碼儘量的簡潔,當然不希望語句塊中存在無關邏輯的轉換實體類的語句,相對來說modelmapper提供了一個比較好的方式
pom依賴

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>${modelmapper.version}</version>
</dependency>
ModelMapper modelMapper = new ModelMapper();
//單個轉換
ProductInfo productInfo = service.getOne();
ProductInfoDto dto = modelMapper.map(productInfo,ProductInfoDto.calss);

//list轉換
 List<ProductInfo> productInfos =service.getList();
            List<ProductInfoDto> productInfoDtos = modelMapper.map(productInfos, new TypeToken<List<ProductInfoDto>>() {
            }.getType());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章