java - 使用 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 的列表。
解决方案
您也应该考虑映射类的“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);
}
如果您仍然卡住,请告诉我。
推荐阅读
- r - 在传单地图上添加迷你雷达图作为标记
- javascript - 如何使用 Fetch 添加动态 URL?
- javascript - 显示带有下标(或下标)样式的菜单项标签
- java - 在被引用为匿名内部类的替代品的视频中看到了这个,它是什么?
- python - 从python中的多个列表中随机选择
- angular - Jhipster 启动非常慢 - 启动空白引导应用程序需要 2 小时
- python - 使用 Pandas(Python) 从 Google Drive 读取非常大的 csv 文件
- sql - 如何在sql中找到count的最大值和最小值
- javascript - 如何在 Selenium Webdriver Javascript 中保存为网页?
- flutter - Flutter - 如何在多个地方重用一些代码