mapstruct – 在复杂对象上下文中将可迭代对象转换为非可迭代对象

huangapple go评论68阅读模式
英文:

mapstruct - iterable to noniterable within complex object context

问题

我目前正在面对 MapStruct,它的初学者问题之一如下所示。

我确实了解示例提案:https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable

而且我也大致知道如何处理复杂映射,但是我在头脑中遇到了一个障碍,想要映射类似于以下内容:

  1. @Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses[0].privateAddresses[0].address")
  2. 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:

  1. @Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses[0].privateAddresses[0].address")
  2. 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 可以帮您处理大部分的映射代码,但对于某些情况,您只需要稍微帮助一下。这就是示例试图演示的内容。

  1. @Mapper
  2. public abstract class MyMapper {
  3. @Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses")
  4. abstract EmployeeDto map(Employee employee);
  5. // 自己实现一个具体的方法,MapStruct 可以识别并在其生成的代码中调用
  6. AddressDto map(List<PrivateAddress> source) {
  7. // 或许需要进行一些空指针检查,然后调用下面由 MapStruct 生成的方法
  8. return map(source.get(0).get(0));
  9. }
  10. // 继续让 MapStruct 完成大部分的工作
  11. abstract AddressDto map(Address source);
  12. }
英文:

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.

  1. @Mapper
  2. public abstract class MyMapper{
  3. @Mapping(target = &quot;employee.mainAddress.address&quot;, source = &quot;employee.registeredAddresses&quot;)
  4. abstract EmployeeDto map(Employee employee);
  5. // implement a concrete method yourself that MapStruct can recognise and call in its generated code
  6. AddressDto map(List&lt;PrivateAddress&gt; source) {
  7. // perhaps do some NPE checking, call MapStruct generated method below
  8. return map( source.get(0).get(0) );
  9. }
  10. // continue letting MapStruct do the bulk of the work
  11. abstract AddressDto map(Address source);
  12. }

huangapple
  • 本文由 发表于 2020年9月26日 02:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64069503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定