A code decorator for MapStruct

1. What is it MapStruct?

1.1 MapStruct

MapStruct official website

MapStructis a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention-over-configuration approach. The generated mapping code uses simple method calls and is therefore fast, type-safe and easy to understand.
When decorating a house, some cables should be routed as far as possible 内线, paying attention to make the room look more tidy and beautiful. MapStructSimplify the conversion of Java Beans like a code decoration expert.

1.2 Add dependencies

 <dependency>
  	   <groupId>org.mapstruct</groupId>
         <artifactId>mapstruct</artifactId>
       <version>1.3.1.Final</version>
  </dependency>

2. Application scenarios

2.1 Equal conversion of field names

2.1.1 Single object conversion

conversion mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
...

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 转 responseDto
     * @param s
     * @return
     */
    StudentResponseDTO entityToResponseDTO(Student s);
}

StudentEntity class before conversion

{
    
    
    "age": 24,
    "className": "一年级五班",
    "entranceTime": "2022-10-18",
    "height": 180.0,
    "name": "我玩亚索我会C",
    "weight": 140.0
}

after conversionStudentResponseDTO

{
    
    
    "className": "一年级五班",
    "name": "我玩亚索我会C"
}

2.1.2 Collection conversion

Conversion Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 转 responseDto list
     * @return
     */
    List<StudentResponseDTO> listEntityToResponseListDto(List<Student> studentes);
}

StudentList collection before conversion

[
    {
    
    
        "age": 24,
        "className": "一年级五班",
        "height": 180.0,
        "name": "我玩亚索我会C",
        "weight": 140.0
    },
    {
    
    
        "age": 25,
        "className": "铃兰五班",
        "height": 184.0,
        "name": "泷谷源治",
        "weight": 130.0
    },
    {
    
    
        "age": 26,
        "className": "铃兰一班",
        "height": 178.0,
        "name": "芹泽多摩雄",
        "weight": 160.0
    },
    {
    
    
        "age": 24,
        "className": "铃兰火箭班",
        "height": 175.0,
        "name": "辰川时生",
        "weight": 120.0
    }
]

converted StudentResponseDTOcollection

[
    {
    
    
        "className": "一年级五班",
        "name": "我玩亚索我会C"
    },
    {
    
    
        "className": "铃兰五班",
        "name": "泷谷源治"
    },
    {
    
    
        "className": "铃兰一班",
        "name": "芹泽多摩雄"
    },
    {
    
    
        "className": "铃兰火箭班",
        "name": "辰川时生"
    }
]

2.2 Field unequal conversion

2.2.1 Single object conversion

When the attribute name in the converted object is not equal to the attribute name in the converted object, use the annotation @Mapping to manually map, indicating the target target, sourceindicating the source, and manual mapping is to sourcemap the attributes in to target the attributes in.

Conversion Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
...

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 转实体
     * @param dto
     * @return
     */
    @Mapping(target = "name",source = "studentName")
    @Mapping(target = "className",source = "studentClassName")
    Student requestDTOToEntity(StudentRequestDTO dto);
}

before conversionStudentRequestDTO

{
    
    
    "studentClassName": "E班",
    "studentName": "林田惠"
}

after conversionStudent

{
    
    
    "className": "E班",
    "name": "林田惠"
}

2.2.2 Collection conversion

When the field unequal sets are converted to each other, two Mappers need to be defined, one is the conversion of a single object, and the other is the conversion of a collection object.

Conversion Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
...
import java.util.List;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 转 responseDto 字段不同
     * @param student
     * @return
     */
    @Mapping(target = "studentName",source = "name")
    @Mapping(target = "studentClassName",source = "className")
    StudentInfoResponseDTO entityToResponseList(Student student);
    /**
     * 转 responseDto list 字段不同
     * @return
     */
    List<StudentInfoResponseDTO> listEntityToResponseLists(List<Student> students);
}

Studentcollection before conversion

[
    {
    
    
        "age": 24,
        "className": "一年级五班",
        "height": 180.0,
        "name": "我玩亚索我会C",
        "weight": 140.0
    },
    {
    
    
        "age": 25,
        "className": "铃兰五班",
        "height": 184.0,
        "name": "泷谷源治",
        "weight": 130.0
    },
    {
    
    
        "age": 26,
        "className": "铃兰一班",
        "height": 178.0,
        "name": "芹泽多摩雄",
        "weight": 160.0
    },
    {
    
    
        "age": 24,
        "className": "铃兰火箭班",
        "height": 175.0,
        "name": "辰川时生",
        "weight": 120.0
    }
]

converted StudentInfoResponseDTOcollection

[
    {
    
    
        "studentClassName": "一年级五班",
        "studentName": "我玩亚索我会C"
    },
    {
    
    
        "studentClassName": "铃兰五班",
        "studentName": "泷谷源治"
    },
    {
    
    
        "studentClassName": "铃兰一班",
        "studentName": "芹泽多摩雄"
    },
    {
    
    
        "studentClassName": "铃兰火箭班",
        "studentName": "辰川时生"
    }
]

2.3 Multiple sources

Some fields are not attributes in the object, but if you want to assign a value to the converted object, you can pass the attribute as a parameter.

Conversion Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
...
import java.util.List;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 额外参数 转 实体类
     * @param dto
     * @param entranceTime 额外参数 入学时间
     * @return
     */
    @Mapping(target = "name",source = "dto.studentName")
    @Mapping(target = "className",source = "dto.studentClassName")
    @Mapping(target = "entranceTime",source = "entranceTime")
    Student extraParamsToEntity(StudentRequestDTO dto,String entranceTime);
}

before conversionStudentRequestDTO

{
    
    
    "studentClassName": "E班",
    "studentName": "林田惠"
}

after conversionStudent

{
    
    
    "className": "E班",
    "entranceTime": "2022-10-18",
    "name": "林田惠"
}

Note: When there are multiple parameters of the mapper method, an alias needs to be specified when manually mapping, such as:@Mapping(target = "name",source = "dto.studentName")

2.4 Default values

To set default values ​​for properties in an object usedefaultValue

import javax.xml.crypto.Data;
import java.time.LocalDateTime;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 默认参数 转 实体类
     * @param dto
     * @return
     */
    @Mapping(target = "className",defaultValue = "五班")
    Student defaultToEntity(StudentRequestDTO dto);
}

2.5 Data type mapping

2.5.1 Date type

Specifies the date format.

import javax.xml.crypto.Data;
import java.time.LocalDateTime;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 日期类型映射 转 实体类
     * @param dto
     * @param entranceTime 入学时间
     * @return
     */
    @Mapping(target = "entranceTime",dateFormat = "yyyy-MM-dd",source = "entranceTime")
    Student dateTypeToEntity(StudentRequestDTO dto,String entranceTime);
}

2.5.2 Numeric types

Round to two decimal places.

import javax.xml.crypto.Data;
import java.time.LocalDateTime;

@Mapper(componentModel = "spring")
public interface StudentMapper {
    
    
    /**
     * 数字类型映射 转 实体类
     * @param dto
     * @param entranceTime 入学时间
     * @return
     */
    @Mapping(target = "tuition",numberFormat = "$#.00",source = "tuitionFee")
    Student dateTypeToEntity(StudentRequestDTO dto,String entranceTime);
}

2.6 Expressions

entranceTimeset to the current time
studentNoset to a random number

@Mapper(componentModel = "spring",imports = {
    
    LocalDateTime.class, UUID.class})
public interface StudentMapper {
    
    
 /**
     * 表达式 转 实体类
     * @param dto
     * @return
     */
    @Mapping(target = "entranceTime",expression = "java(LocalDateTime.now())")
    @Mapping(target = "studentNo",expression = "java(UUID.randomUUID().toString())")
    List<Student> expressionToEntities(List<StudentRequestDTO> dto);
}

3. Precautions

When using MapStruct, if there is a change in the mapped field, be sure to clearclear the compiled file and recompile install.

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/127393581