java Dozer:将单个字段映射到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11262525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dozer: Map single field into a List
提问by user424174
How do you map a single field into a List
/ Collection
in Dozer?
如何将单个字段映射到Dozer 中的List
/ Collection
?
class SrcFoo {
private String id;
private List<SrcBar> bars;
}
class SrcBar {
private String name;
}
Here are my destination objects:
这是我的目标对象:
class DestFoo {
private List<DestBar> destBars;
}
class DestBar {
private String fooId; // Populated by SrcFoo.id
private String barName;
}
I want all DestBar.fooId
(entire list of DestBars) to be populated with SrcFoo.id
我希望所有DestBar.fooId
(DestBars 的整个列表)都填充SrcFoo.id
This question is similar to this one posted here, expect I want to map my single field to every item in the list. Dozer: map single field to Set
这个问题类似于这里发布的这个问题,希望我想将我的单个字段映射到列表中的每个项目。Dozer:将单个字段映射到 Set
I tried the following, but it only populated DestBar.fooId
for the first item in the list.
我尝试了以下操作,但它只DestBar.fooId
为列表中的第一项填充。
<mapping>
<class-a>SrcFoo</class-a>
<class-b>DestFoo</class-b>
<field>
<a>bars</a>
<b>destBars</b>
</field>
<field>
<a>id</a>
<b>destBars.fooId</b> <!-- same affect as destBars[0].fooId ? -->
</field>
</mapping>
采纳答案by davidmontoyago
Dozer does not support that type of mapping. In order to do that type of mapping, you would have to know the indexes on your Collection (static mapping). This a Job for a custom converter, Create a converter of String to List (of DestBar) like this:
Dozer 不支持这种类型的映射。为了进行这种类型的映射,您必须知道集合上的索引(静态映射)。这是自定义转换器的工作,创建一个字符串转换器到列表(DestBar),如下所示:
public class YourConverter extends DozerConverter<String, List>
Implement the mapping logic in your converter (Just set the String Id where required) and configure your dozer file like this:
在您的转换器中实现映射逻辑(只需在需要的地方设置字符串 ID)并像这样配置您的推土机文件:
<mapping>
<class-a>SrcFoo</class-a>
<class-b>DestFoo</class-b>
...
<field custom-converter="yourpackage.YourConverter">
<a>id</a>
<b>destBars</b>
</field>
</mapping>