MapStruct对象转换

MapStruct对象转换

1.数据传输对象

在开发过程中用于数据传输的对象有MerchantRegisterVO、MerchantDTO、entity(实体类),它们的用途如下:

1、MerchantRegisterVO  用于应用层接收前端请求及响应前端数据。
2、MerchantDTO   用于服务层传入及响应数据。
3、entity(实体类) 用于持久层传入及响应数据。

数据传输对象(Data Transfer Object)是系统在交互过程中根据需要及规范将数据封装到数据对象中进行传输。
本项目数据传输对象的规范:
1、应用层
如没有接口参数的特殊要求,应用层使用DTO结尾的对象传输,否则单独定义VO结尾的对象传输。
2、服务层
统一使用DTO结尾的对象传输。
3、持久层
统一使用Entity对象传输。

2.MapStruct解决数据传输对象转换的繁琐

MapStruct是一个代码生成器,它基于约定优于配置的方法大大简化了Java Bean对象之间的映射转换的实现。
MapStruct 使用简单的方法即可完成对象之间的转换,它速度快、类型安全且易于理解

官方地址: https://mapstruct.org/
2.1.在工程添加MapStruct依赖:
<dependency>
	<groupId>org.mapstruct</groupId>
	<artifactId>mapstruct‐jdk8</artifactId>
	<version>1.3.0.Final</version>
</dependency>
<dependency>
	<groupId>org.mapstruct</groupId>
	<artifactId>mapstruct‐processor</artifactId>
	<version>1.2.0.Final</version>
</dependency>
2.2.服务层对象转换

定义MerchantConvert转换类,使用@Mapper注解快速实现对象转换:

package com.shanjupay.merchant.convert;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.entity.Merchant;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface MerchantCovert {

	MerchantCovert INSTANCE = Mappers.getMapper(MerchantCovert.class);
	
	MerchantDTO entity2dto(Merchant entity);
	
	Merchant dto2entity(MerchantDTO dto);
}

在MerchantCovert中定义测试方法:

public static void main(String[] args) {
	//dto转entity
	MerchantDTO merchantDTO = new MerchantDTO();
	merchantDTO.setUsername("测试");
	merchantDTO.setPassword("111");
	Merchant entity = MerchantCovert.INSTANCE.dto2entity(merchantDTO);
	//entity转dto
	entity.setMobile("123444554");
	MerchantDTO merchantDTO1 = MerchantCovert.INSTANCE.entity2dto(entity);
	System.out.println(merchantDTO1);
}

List数据也可以转换:
在MerchantCovert中定义list的方法,如下:

//list之间的转换
List<MerchantDTO> listentity2dto(List<Merchant> list);

测试:
在main方法编写list之间的转换测试:

//测试list之间的转换
List<Merchant> list_entity = new ArrayList<>();
list_entity.add(entity);
List<MerchantDTO> merchantDTOS = MerchantCovert.INSTANCE.listentity2dto(list_entity);

System.out.println(merchantDTOS);
2.3.应用层对象转换
package com.shanjupay.merchant.convert;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface MerchantRegisterConvert {

	MerchantRegisterConvert INSTANCE = Mappers.getMapper(MerchantRegisterConvert.class);
	
	MerchantDTO vo2dto(MerchantRegisterVO vo);
	
	MerchantRegisterVO dto2vo(MerchantDTO dto);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曙光][照亮黑夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值