英文:
mapstruct - iterable to noniterable within complex object context
问题
我目前正在面对 MapStruct,它的初学者问题之一如下所示。
我确实了解示例提案:https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable
而且我也大致知道如何处理复杂映射,但是我在头脑中遇到了一个障碍,想要映射类似于以下内容:
@Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses[0].privateAddresses[0].address")
abstract EmployeeDto map(Employee employee);
希望对象结构清楚。在源中有两个列表,对于每个列表都应选择第一个元素。MapStruct 如何实现这一点呢?
英文:
I am currently facing mapstruct and it's beginner issues and one of them is the following.
I do know the samples proposal: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable
And i do know generally to handles complex mappings, BUT i really got a blockade in my head mapping something like:
@Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses[0].privateAddresses[0].address")
abstract EmployeeDto map(Employee employee);
Hope that the object structure is clear. in the source there are two lists and for each the first element should be chosen. How can this be done by mapstruct?
答案1
得分: 2
只需自己指定一个映射方法。MapStruct 可以帮您处理大部分的映射代码,但对于某些情况,您只需要稍微帮助一下。这就是示例试图演示的内容。
@Mapper
public abstract class MyMapper {
@Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses")
abstract EmployeeDto map(Employee employee);
// 自己实现一个具体的方法,MapStruct 可以识别并在其生成的代码中调用
AddressDto map(List<PrivateAddress> source) {
// 或许需要进行一些空指针检查,然后调用下面由 MapStruct 生成的方法
return map(source.get(0).get(0));
}
// 继续让 MapStruct 完成大部分的工作
abstract AddressDto map(Address source);
}
英文:
Just specify a Mapping method yourself. MapStruct can take the burden of most of your mapping code, but for some, you just need to help out a little. That's what the example tries to demonstrate.
@Mapper
public abstract class MyMapper{
@Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses")
abstract EmployeeDto map(Employee employee);
// implement a concrete method yourself that MapStruct can recognise and call in its generated code
AddressDto map(List<PrivateAddress> source) {
// perhaps do some NPE checking, call MapStruct generated method below
return map( source.get(0).get(0) );
}
// continue letting MapStruct do the bulk of the work
abstract AddressDto map(Address source);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论