MapStruct集成进行Bean的转换
MapStruct集成
依赖
<mapstruct.version>1.5.2.Final</mapstruct.version>
<lombok.version>1.18.16</lombok.version>
<!--MapStruct相关依赖-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>compile</scope>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
实体类
@Data
@EqualsAndHashCode(callSuper = false)
public class Member {
private Long id;
private String username;
private String password;
private String nickname;
private Date birthday;
private String phone;
private String icon;
private Integer gender;
}
@Data
@EqualsAndHashCode(callSuper = false)
public class MemberDto {
private Long id;
private String username;
private String password;
private String nickname;
//与PO类型不同的属性
private String birthday;
//与PO名称不同的属性
private String phoneNumber;
private String icon;
private Integer gender;
}
编写mapper接口
@Mapper
public interface MemberMapper {
MemberMapper INSTANCE = Mappers.getMapper(MemberMapper.class);
@Mapping(source = "phone", target = "phoneNumber")
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd")
MemberDto toDto(Member member);
/**
* 支持集合映射的功能
* @param memberList
* @return
*/
@Mapping(source = "phone", target = "phoneNumber")
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd")
List<MemberDto> toDtoList(List<Member> memberList);
}
使用
@RestController
@RequestMapping("/mapStruct")
public class MapStructController {
@GetMapping("/baseMapping")
public CommonResultVo<MemberDto> baseTest() {
Member member = new Member();
member.setBirthday(new Date());
member.setPhone("13074076522");
member.setGender(1);
MemberDto memberDto = MemberMapper.INSTANCE.toDto(member);
return CommonResultVo.success(memberDto);
}
}
详细使用参考
https://juejin.cn/post/7026151729997561869?share_token=68a5864a-10f9-414d-a9b9-68da7bac1824