Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to merge two source objects into target object using mapstruct ,here one field in source1 has List and in source2 that is string

Tags:

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 has only one value means list.size()=1. If source1 name is empty then it has to take from source2. And target should contain all the fields even-though those are not available in one source

like image 261
G SriHAri Avatar asked Oct 24 '25 02:10

G SriHAri


1 Answers

try:

@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
   }


}
like image 109
Sjaak Avatar answered Oct 26 '25 20:10

Sjaak