kotlin的mapstruct的使用案例,将一个对象转化为另一个对象

x33g5p2x  于2022-05-19 转载在 Java  
字(2.2k)|赞(0)|评价(0)|浏览(416)

当项目开发中涉及到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)

如何实现的呢?

第一、定义interface 能力

@Mapper
interface CmdbProductConverter {

	fun convertToCmdbProduct(product: Cmdb.Product): CmdbProduct
}

第二、idea bulid 产生CmdbProductConverterImpl()方法

第三、在使用的地方就直接使用CmdbProductConverterImpl()进行转化

return cmdbGrpcClient.list(
			Cmdb.ListRequest.newBuilder().setProduct(cmdbProduct).build()
		).productsList.map { product ->
			CmdbProductConverterImpl().convertToCmdbProduct(product)
		}

具体使用方法,可以参考:
https://blog.csdn.net/qq_40194399/article/details/110162124

相关文章