@Data
public class Student {
private Long id;
private String name;
private Long idCard;
private LocalDate birthday;
}
@Data
public class StudentDTO {
private Long userId;
private Long idCard;
private String userName;
private String idNumber;
private LocalDate dateOfBirth;
private Long phone;
}
@Mapper(implementationName = "StudentConvertUtil",
implementationPackage = "com.ylz.mapstruct.domain.convert.impl")
public interface IStudentConvert {
IStudentConvert INSTANCE = Mappers.getMapper(IStudentConvert.class);
@Mapping(source = "id", target = "userId")
@Mapping(source = "name", target = "userName")
@Mapping(source = "name", target = "idNumber")
@Mapping(source = "birthday", target = "dateOfBirth")
@Mapping(source = "newIdCard", target = "idCard")
StudentDTO student2StudentDTO(Student student, Long phone, Long newIdCard);
@BeforeMapping
default void preProcess() {
System.out.println("执行前置处理......");
}
@AfterMapping
default StudentDTO postProcess(@MappingTarget StudentDTO studentDTO, Student。student, Long phone) {
System.out.println("转换Student:" + student);
studentDTO.setPhone(phone);
}
}
@Mapping(source = "persionDTO.describe", target = "des")
@Mapping(source = "apee.ap", target = "choice")
public abstract PersonVO transToViewObject(PersionDTO persionDTO, Apee apee);
生成代码如下
@Override
public PersonVO transToViewObject(PersionDTO persionDTO, Apee apee) {
if ( persionDTO == null && apee == null ) {
return null;
}
PersonVO personVO = new PersonVO();
if ( persionDTO != null ) {
personVO.setDes( persionDTO.getDescribe() );
personVO.setPId( persionDTO.getPId() );
personVO.setName( persionDTO.getName() );
personVO.setAge( persionDTO.getAge() );
personVO.setSex( persionDTO.getSex() );
}
if ( apee != null ) {
personVO.setChoice( apee.getAp() );
}
changeDateIntoStr( personVO, persionDTO );
return personVO;
}
当你的多个对象作为入参时,多个对象均含有同一个属性时即当目标对象与另外多个入参都含有一个或多个相同属性时,在mapping 也需要指定,否则不知道拿哪个属性会抛出异常。
@Mapping(source = "persionDTO.describe", target = "des")
@Mapping(source = "apee.ap", target = "choice", defaultValue = "给个默认值")
public abstract PersonVO transToViewObject(PersionDTO persionDTO, Apee apee);
@Mapping(source = "describe", target = "des")
@Mapping(source = "apee", target = "apee2")
public abstract PersonVO transToViewObject(PersionDTO persionDTO);
@InheritInverseConfiguration
public abstract PersionDTO transToViewObject(PersonVO personVO);
参考链接Mapstruct @Mapper @Mapping 使用介绍以及总结_极光雨雨的博客-CSDN博客