MapStruc实现DTO装DO

MapStruct实现DTO转DO

引入jar包

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

两个要转换的类

public class Car {
    private String make;
    private int numberOfSeats;
    private String carType;

    public Car() {
    }

    public Car(String make, int numberOfSeats, String carType) {
        this.make = make;
        this.numberOfSeats = numberOfSeats;
        this.carType = carType;
    }

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public int getNumberOfSeats() {
        return numberOfSeats;
    }

    public void setNumberOfSeats(int numberOfSeats) {
        this.numberOfSeats = numberOfSeats;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }
public class CarDTO {
    private String make;
    private int seatCount;
    private String type;

    public CarDTO() {
    }

    public CarDTO(String make, int seatCount, String type) {
        this.make = make;
        this.seatCount = seatCount;
        this.type = type;
    }

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public int getSeatCount() {
        return seatCount;
    }

    public void setSeatCount(int seatCount) {
        this.seatCount = seatCount;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

创建一个映射器接口

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

@Mapper
public interface CarMapper {
    CarMapper Covert = Mappers.getMapper(CarMapper.class);
            @Mapping(source = "numberOfSeats", target = "seatCount")
            @Mapping(source = "carType", target = "type")
    CarDTO carToCarDTO(Car car);
}
  • @Mapper注释将该接口标记为映射接口,并让 MapStruct 处理器在编译期间启动。
  • 对于源对象和目标对象中具有不同名称的属性,@Mapping可以使用注解来配置名称。

测试

public class CarTest {
    public static void main(String[] args) {
        Car car = new Car("1122",1,"fasd");
        CarDTO carDTO = CarMapper.Covert.carToCarDTO(car);
        System.out.println(carDTO.getSeatCount());
        System.out.println(carDTO.getMake());
        System.out.println(carDTO.getType());
    }
}
```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值