首页 > 解决方案 > 使用 MapStruct 将 Dto 转换为实体会出错

问题描述

我正在尝试使用MapStruct创建“PersonDto”类到“PersonEntity”的映射器

请考虑以下 Entity、Dto 和 Mapper 类。

个人实体.java

package com.example.car;

import java.util.ArrayList;
import java.util.List;

public class PersonEntity {
    private String name;
    private List<CarEntity> cars;

    public PersonEntity() {
        cars = new ArrayList<>();
    }

    public boolean addCar(CarEntity carEntitiy) {
        return cars.add(carEntitiy);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<CarEntity> getCars() {
        return cars;
    }

    public void setCars(List<CarEntity> carEntities) {
        this.cars = carEntities;
    }
}

CarEntity.java

package com.example.car;

public class CarEntity {
    private String model;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }
}

PersonDto.java

package com.example.car;

import java.util.ArrayList;
import java.util.List;

public class PersonDto {
    private String name;
    private List<CarDto> cars;

    public PersonDto() {
        cars = new ArrayList<>();
    }

    public boolean addCar(CarDto carDto) {
        return cars.add(carDto);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<CarDto> getCars() {
        return cars;
    }

    public void setCars(List<CarDto> carDtos) {
        this.cars = carDtos;
    }
}

CarDto.java

package com.example.car;

public class CarDto {
    private String model;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }
}

人物映射器

package com.example.car;

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

@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface PersonMapper {

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

    PersonEntity personDtoToPersonEntity(PersonDto personDto);
}

当我尝试使用链接提供的 Maven 指令生成代码时,我收到以下错误:

无法将属性“java.util.List cars”映射到“com.example.car.CarEntity cars”。考虑声明/实现一个映射方法:“com.example.car.CarEntity map(java.util.List value)”。

如果我从 Person 类中删除“adder”方法,它工作正常。但我真的很想使用加法器方法(用于 JPA 实体父子关系的目的)。

我不确定为什么 MapStruct 不将 PersonEntity 中的 cars 属性解释为 List。它将该属性解释为一个简单的 CarEntity 而不是 CarEntity 的列表。

标签: javaspring-bootentitydtomapstruct

解决方案


您也应该考虑映射类的“Has-A”属性
只需包括 CarEntity carDtoToCarEntity(CarDto carDto)
这是代码片段:

@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface PersonMapper {
    PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class);
    CarEntity carDtoToCarEntity(CarDto carDto); 
    PersonEntity personDtoToPersonEntity(PersonDto personDto);

}

如果您仍然卡住,请告诉我。


推荐阅读