对象之间的转换
1、在maven中引入jar包
<!--对象转换--> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.1.0.Final</version> <scope>provided</scope> </dependency>
2、创建一个接口专门实现对象进行转换
@Mapper public interface IContractBean { IContractBean INSTANCE = Mappers.getMapper(IContractBean.class); Contract contract(SaveContractDTO saveContactDTO); ContractGood contractGood(GoodDTO goodDTO); List<ContractGood> contractGood(List<GoodDTO> goodDTOList); @Mappings({ @Mapping(source = "terminationTime", target = "endTime"), }) ContractAssistVO relationVO(ContractRelationAssist relationAssist); Page<ContractAssistVO> relationVO(Page<ContractRelationAssist> relationAssistPage); }
如果是List对象互相转换,那么需要先设置List里面的对象先进行转换
ContractGood contractGood(GoodDTO goodDTO); List<ContractGood> contractGood(List<GoodDTO> goodDTOList);
如果对象里面的属性不一致,需要进行转换,则使用@Mappings注解
//将 terminationTime 转成 endTime对象 @Mappings({ @Mapping(source = "terminationTime", target = "endTime"), }) ContractAssistVO relationVO(ContractRelationAssist relationAssist); Page<ContractAssistVO> relationVO(Page<ContractRelationAssist> relationAssistPage);
3、实现类进行使用
GoodVO goodVO = IContractBean.INSTANCE.contractGoodVO(contractGood); List<GoodVO> goodVOList = IContractBean.INSTANCE.contractGoodVO(goodList);