java - 使用 MapStruct 映射嵌套字段
问题描述
假设我有这些实体:
public class Address {
private String id;
private String address;
private City city;
}
public class City {
private int id;
private Department department;
private String zipCode;
private String name;
private Double lat;
private Double lng;
}
public class Department {
private int id;
private Region region;
private String code;
private String name;
}
public class Region {
private int id;
private String code;
private String name;
}
而这个 DTO:
public class AddressDTO {
private String address;
private String department;
private String region;
private String zipCode;
}
在我的 DTO 中,我想映射
- 来自城市/部门/名称的部门
- 来自城市/部门/地区/名称的区域
这是我的映射器:
@Mapper(componentModel = "spring")
public interface AddressMapper {
AddressDTO addressToAddressDTO(Address item);
}
解决方案
当您映射嵌套字段时,您需要告诉 MapStruct 从哪里以及如何使用@Mapping
.
在你的情况下,它看起来像:
@Mapper(componentModel = "spring")
public interface AddressMapper {
@Mapping(target = "department", source = "city.department.name")
@Mapping(target = "region", source = "city.department.region.name")
@Mapping(target = "zipCode", source = "city.zipCode")
AddressDTO addressToAddressDTO(Address item);
}
推荐阅读
- sql - 查询优化/重写
- git - 如何让我的网络服务器从我的仓库自动更新?
- python - 错误:关机后无法注册 atexit
- google-oauth - Facebook/Google 登录 API,如何确保用户不是机器人
- python - 如何使用云运行python api从大查询表中读取大数据以及系统配置应该是什么?
- php - Laravel 如何让 Auth 类在不同的模型而不是用户上执行函数
- python - Kivymd:无法在 Scrollview 中添加多个文本字段和按钮
- sql - SQL FOR XML 属性和值
- php - 使用 FTP 类从 codeigniter 2 中的 ftp 下载文件
- node.js - 对于 next.js proejct 的纱线工作区子包,我应该使用 commonjs 还是 es 模块?