您好,登錄后才能下訂單哦!
這篇文章主要介紹“mapstruct的qualifiedByName怎么用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“mapstruct的qualifiedByName怎么用”文章能幫助大家解決問題。
可用于格式化小數位等,在po轉換為vo時就已格式化小數位完成,所以不必單獨再寫代碼處理小數位。
1 引用pom1 ,能正常使用mapstruct的注解,但不會生成Impl類
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>1.2.0.Final</version> </dependency>
引用pom2 才會生成Impl類
2 定義ConvertMapper
package com.weather.weatherexpert.common.model.mapper; import com.weather.weatherexpert.common.model.po.AreaPO; import com.weather.weatherexpert.common.model.vo.AreaVO; import org.mapstruct.MapMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import org.mapstruct.factory.Mappers; import java.text.DecimalFormat; /** * <p>Title: </p> * <p>Description: </p> * */ @Mapper public interface ConvertMapper { ConvertMapper INSTANCE = Mappers.getMapper(ConvertMapper.class); @Mapping(source = "pm25", target = "pm25", qualifiedByName = "formatDoubleDef") AreaVO areaPO2areaVO(AreaPO areaPO); @Named("formatDoubleDef")//需要起個名字,不然報錯,可以與方法名一致,當然也可以不一致 default Double formatDouble(Double source) { DecimalFormat decimalFormat = new DecimalFormat("0.00");//小數位格式化 if (source == null) { source = 0.0; } return Double.parseDouble(decimalFormat.format(source)); } }
3 定義源類和目標類
public class AreaPO { private String cityName; private Integer haveAir; private Double pm25; private String pm10Str; ............ } public class AreaVO { private String cityName; private Integer haveAir; private Double pm25; private String pm25Str; private Double pm10; ...... }
4 看生成的Impl類ConvertMapperImpl
package com.weather.weatherexpert.common.model.mapper; import com.weather.weatherexpert.common.model.po.AreaPO; import com.weather.weatherexpert.common.model.vo.AreaVO; public class ConvertMapperImpl implements ConvertMapper { public ConvertMapperImpl() { } public AreaVO areaPO2areaVO(AreaPO areaPO) { if (areaPO == null) { return null; } else { AreaVO areaVO = new AreaVO(); areaVO.setPm25(this.formatDouble(areaPO.getPm25())); areaVO.setCityName(areaPO.getCityName()); areaVO.setHaveAir(areaPO.getHaveAir()); return areaVO; } }
5 測試
AreaPO areaPO = new AreaPO("忻州", 1, 1.256879); AreaVO areaVO = ConvertMapper.INSTANCE.areaPO2areaVO(areaPO); logger.info("JSON.toJSONString(areaVO):" + JSON.toJSONString(areaVO));
輸出:
JSON.toJSONString(areaVO):{“cityName”:“忻州”,“haveAir”:1,“pm25”:1.26}
關于“mapstruct的qualifiedByName怎么用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。