java - Mapstruct 将一个字段映射到多个目标字段,反之亦然
问题描述
我已经提到了使用 Mapstruct 将多个源字段映射到相同类型的目标字段的问题,但它没有帮助
我的休息资源类如下
class Base {
//fields
//getters and setters
}
Class A extends Base{
List<String> emailAdddress;
//other fields
//getters and setters
}
Class B extends Base{
List<String> devices;
//other fields
//getters and setters
}
Class C extends Base{
List<String> mobileNumbers;
//other fields
//getters and setters
}
我的实体类是 Source,如下所示:
Class Source {
String address
//other fields
//getters and setters
}
我想在我的映射器类中使用 emailAddress 或 devices 或 mobileNumbers 映射 Source 类的地址,我尝试在映射器类和装饰器类中使用 @AfterMapping 但它没有帮助。
我有一个像这样的映射器类
@Mapper
public abstract class AddressMapper {
//basic mappings here
public abstract Source toEntity(Base b);
public abstract Base toDomain(Source src);
@AfterMapping
public void setAddressInfo(@MappingTarget Source src, B b) {
src.setAddress(b.getDevices().toString());
}
解决方案
我不确定我是否完全遵循您正在尝试做的事情。
但是,如果要映射特定类 ( A
, B
,C
则需要将它们放在方法中。由于 MapStruct 是一个注释处理器,并且在编译期间它只知道Base
示例中的字段。你可以做的是类似以下:
@Maper
public interface AdressMapper {
default Source toEntity(Base b) {
if (b == null) {
return null;
} else if (b instanceOf A) {
toEntity((A) b);
} else if (b instanceOf B) {
toEntity((A) b);
} else if (b instanceOf C) {
toEntity((C) b);
} else {
// Decide what to do
}
}
@Mapping(target = "address", source = "emailAddress")
Source toEntity(A a);
@Mapping(target = "address", source = "devices")
Source toEntity(B b);
@Mapping(target = "address", source = "mobileNumbers")
Source toEntity(C c);
default Base toDomain(Source source) {
if (source == null) {
return null;
} else if (condition to match to A) {
return toDomainA(source);
} else if (condition to match to B) {
return toDomainB(source);
} else if (condition to match to C) {
return toDomainC(source);
}
}
@Mapping(target = "emailAddress", source = "address")
A toDomainA(Source source);
@Mapping(target = "devices", source = "address")
B toDomainB(Source source);
@Mapping(target = "mobileNumbers", source = "address")
C toDomainB(Source source);
// This method is needed so MapStruct knows how to map from List<String> into String
static <T> String listToString(List<T> list) {
if (list == null) {
return null;
}
return list.toString();
}
// This method is needed so MapStruct know hot to map from String into List<String>
static List<String> fromListToString(String string) {
if (string == null) {
return null;
}
// Perform your own conversion
}
}
推荐阅读
- php - 使用 PHP 将嵌套 JSON 从 URL 响应转换为平面 JSON
- html - 当我的列数设置为 4 时,为什么我的 CSS 列会出现故障?
- python - 每 5 分钟执行一次任务的 Python 脚本随机保持空闲状态,直到 ctrl-c
- javascript - Spring PostMapping 接收具有空值的对象
- css - 为什么我的 css 被 scss 覆盖,甚至不包括在内
- php - WordPress 特色图片请求返回未知
- javascript - QuietJs - 离子 3 错误
- angularjs - 从前端客户端访问超级账本作曲家休息服务器访问令牌
- python - 在 Pandas DataFrame 图中填充缺失值
- python-3.x - Pythons requests.session cookie 检索问题