需要使用mapstruct将两个源对象合并到目标对象中,其中source1中的一个字段具有List,而source2中的一个字段为字符串

时间:2019-04-18 14:43:29

标签: java mapstruct

public class Source1 {
    private String name;               //srihari  
    private List<String> city_names;   //city_names.add("hyderabad-india")
 }
public class Soruce2 {
    private String name;
    private String city_name;            //hyderabad-india
    private List<String> technologies;   //Arrays.asList("java","mapstruct")
 }
public class Target {
    private String name;            // Result: srihari 
    private String city_names;      // Result: hyderabad-india
    private String technologies;    // Result: java, mapstruct
}`

list只有一个值表示list.size()= 1。如果source1名称为空,则必须取自source2。目标应该包含所有字段,即使这些字段在一个源中不可用

1 个答案:

答案 0 :(得分:2)

尝试:

@Mapper
public interface MyMapper{

   // will map all other fields that you specify
   @Mapping( target = "city_names", ignore = true )
   @Mapping( target = "technologies", ignore = true )
   Target map(Source1 s1, Soruce2 s2);

   default map(Source1 s1, Soruce2 s2, @MappingTarget Target t) {
      // do whatever you like with city_names and technologies
   }


}