如何使用 Mapstruct 映射包含列表的对象
How to Map an object contains a List with Mapstruct
鉴于来源 class 定义如下:
class Source{
private String name;
private int age;
private List<Phone> phones;
// getters and setters
}
和 Phone class 定义如下:
class Phone{
private Long id;
private String phoneNumber;
// getters and setters
}
和目标 class 定义如下:
class Target{
private String name;
private int age;
private List<Long> idsPhones;
// getters and setters
}
我有一个界面是:
@Mapper
interface MyMapper{
Target toTarget(Source source);
Source toSource(Target target);
}
如何将 Phone 列表从源 class 映射到目标 Class 中的 idsPhone 列表,反之亦然?
为了实现这一点,您需要通过告诉如何从 Phone
映射到 Long
来帮助 MapStruct。反之亦然。
您的映射器需要类似于:
@Mapper(uses = PhoneRepository.class)
interface MyMapper {
@Mapping(target = "idsPhones", source = "phones")
Target toTarget(Source source);
@InheritInverseMapping
Source toSource(Target target);
default Long fromPhone(Phone phone) {
return phone.getId();
}
}
如果您的 PhoneRepository
包含接受 Long
和 returns Phone
的方法,那么 MapStruct 将自动知道要做什么并调用该方法。
鉴于来源 class 定义如下:
class Source{
private String name;
private int age;
private List<Phone> phones;
// getters and setters
}
和 Phone class 定义如下:
class Phone{
private Long id;
private String phoneNumber;
// getters and setters
}
和目标 class 定义如下:
class Target{
private String name;
private int age;
private List<Long> idsPhones;
// getters and setters
}
我有一个界面是:
@Mapper
interface MyMapper{
Target toTarget(Source source);
Source toSource(Target target);
}
如何将 Phone 列表从源 class 映射到目标 Class 中的 idsPhone 列表,反之亦然?
为了实现这一点,您需要通过告诉如何从 Phone
映射到 Long
来帮助 MapStruct。反之亦然。
您的映射器需要类似于:
@Mapper(uses = PhoneRepository.class)
interface MyMapper {
@Mapping(target = "idsPhones", source = "phones")
Target toTarget(Source source);
@InheritInverseMapping
Source toSource(Target target);
default Long fromPhone(Phone phone) {
return phone.getId();
}
}
如果您的 PhoneRepository
包含接受 Long
和 returns Phone
的方法,那么 MapStruct 将自动知道要做什么并调用该方法。