Mapstruct

1.使用

Student

@Data
public class Student {

    private Long id;

    private String name;

    private Long idCard;

    private LocalDate birthday;
}

StudentDTO

@Data
public class StudentDTO {

    private Long userId;

    private Long idCard;

    private String userName;

    private String idNumber;

    private LocalDate dateOfBirth;

    private Long phone;

}

StudentConvert

@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);
    }
}

StudentConvert生成的实现类

2.多个入参转为一个对象

    @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 也需要指定,否则不知道拿哪个属性会抛出异常。

3.当源属性没有时指定默认值

    @Mapping(source = "persionDTO.describe", target = "des")
    @Mapping(source = "apee.ap", target = "choice", defaultValue = "给个默认值")
    public abstract PersonVO transToViewObject(PersionDTO persionDTO, Apee apee);

4.逆映射

    @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博客

你可能感兴趣的:(java,开发语言)