MapStruct Tutorial

1. Official website

MapStruct - Java bean mappings, the easy way! https://mapstruct.org/

Two, the simplest use

Goal: Convert the data of the entity class Car into CarDto

import lombok.Data;

@Data
public class Car {
    private Long id;
    private String name;
    private Integer numberOfSeats;
    private String type;
}
import lombok.Data;

@Data
public class CarDto {
    private String name;
    private Integer numberOfSeats;
    private String type;
}

3. Define the converter

import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface CarConverter {

    CarConverter INSTANCE = Mappers.getMapper(CarConverter.class);

    CarDto carToCarDto(Car car);
}

4. Business use

public static void main(String[] args) {
        Car car = new Car();
        car.setId(1L);
        car.setName("红旗H6");
        car.setNumberOfSeats(5);
        car.setType("至尊版");

        CarDto carDto = CarConverter.INSTANCE.carToCarDto(car);
        System.out.println(carDto);
    }

5. Mapping of different field names

6. Multi-source mapping

Seven, batch conversion

Guess you like

Origin blog.csdn.net/wenxingchen/article/details/130321645