当项目开发中涉及到dto的对象之间的转化,如下图所示,将grep中的cmdb.product转化为CmdbProduct对象,如下图所示:
return cmdbGrpcClient.list(
Cmdb.ListRequest.newBuilder().setProduct(cmdbProduct).build()
).productsList.map { product ->
CmdbProduct(
skuId = product.skuId,
fastoneStrategy = product.fastoneStrategy,
productLevel = product.productLevel,
fastoneRegion = product.fastoneRegion,
vendor = product.vendor,
productType = ProductType.valueOf(product.productType),
systemPlatform = SystemPlatform.valueOf(product.systemPlatform),
fastoneModel = product.fastoneModel,
fastoneFamily = product.fastoneFamily,
vendorModel = product.vendorModel,
payType = product.payType,
price = product.price.toBigDecimal(),
priceUnit = product.priceUnit,
effectiveTime = product.effectiveTime,
fastoneType = product.fastoneType,
core = product.core.toInt(),
vCpu = product.vCpu.toInt(),
memory = product.memory.toInt(),
gpu = takeIf { product.gpu != "" }?.let { Integer.valueOf(product.gpu) } ?: 0,
gpuMemory = takeIf { product.gpuMemory != "" }?.let { Integer.valueOf(product.gpuMemory) } ?: 0,
gpuType = product.gpuType,
networkBandwidth = product.networkBandwidth,
networkBandwidthUnit = product.networkBandwidthUnit,
temporaryStorage = product.temporaryStorage,
storageUnit = product.storageUnit,
cpuModel = product.cpuModel,
cpuFrequency = product.cpuFrequency,
throughput = product.throughput,
throughputUnit = product.throughputUnit,
iops = product.iops,
iopsUnit = product.iopsUnit,
protocol = product.protocol,
remark = product.remark,
shutdownable = product.shutdownable
)
}
但是这种方法,如果遇到类很大,并且字段都一样的实体,就会显得很臃肿。
现在介绍一种更好的方法:mapstruct
return cmdbGrpcClient.list(
Cmdb.ListRequest.newBuilder().setProduct(cmdbProduct).build()
).productsList.map { product ->
CmdbProductConverterImpl().convertToCmdbProduct(product)
}
上面的代码转化为一句话
CmdbProductConverterImpl().convertToCmdbProduct(product)
如何实现的呢?
@Mapper
interface CmdbProductConverter {
fun convertToCmdbProduct(product: Cmdb.Product): CmdbProduct
}
return cmdbGrpcClient.list(
Cmdb.ListRequest.newBuilder().setProduct(cmdbProduct).build()
).productsList.map { product ->
CmdbProductConverterImpl().convertToCmdbProduct(product)
}
具体使用方法,可以参考:
https://blog.csdn.net/qq_40194399/article/details/110162124
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sunyuhua_keyboard/article/details/124860779
内容来源于网络,如有侵权,请联系作者删除!