mapstruct简单用法

什么是mapstruct?

mapstruct是一种 实体类 映射框架,能够通过Java注解将一个实体类的属性安全地赋值给另一个实体类。有了mapstruct,只需要定义一个映射器接口,声明需要映射的方法,在编译过程中,mapstruct会自动生成该接口的实现类,实现将源对象映射到目标对象的效果。
参考博客:https://blog.csdn.net/Mango_Bin/article/details/125168370

简单使用案例:
引入依赖:
参考博客:https://blog.csdn.net/qq_40241957/article/details/121560381

  <lombok.version>1.18.12</lombok.version>
  <mapstruct.version>1.4.2.Final</mapstruct.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>


实体类
Student.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private String id;
    private String name;
    private String phone;
}

StudentVo .java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentVo {
    private String id;
    private String studentId;
	private String name;
	private String phoneNum;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentResponse {
    private String id;
	private String phone;
}

Mapper

@Mapper
public interface StudentMapStruct {
    StudentMapStruct INSTANCE = Mappers.getMapper(StudentMapStruct.class);
	
    @Mappings({
        @Mapping(source = "id", target = "studentId"),
        @Mapping(target = "id", ignore = true)
    })
    StudentVo studentToVo(Student student);

    @Mapping(target = "phone", ignore = true)
    StudentResponse studentToResponse(CompleteJobRequest completeJobRequest);
}

service层

@Service
public class StudentService {
    public StudentResponse getStudentResponse(Student student) {
		StudentResponse studentRes = StudentMapStruct.INSTANCE.studentToResponse(student);
        return studentRes;
    }

    public StudentVo getStudentVo(Student student) {
		StudentVo studentVo = StudentMapStruct.INSTANCE.studentToVo(student);
        return studentVo;
    }
}

你可能感兴趣的:(java)