How to map from Model entity with list of Objects and one more Object to single Domain entity with Mapstruct

Viewed 217

How can I use MapStruct to create a mapper that maps from Model entity that includes one list of objects and one another object to Domain entity, consists of only list of nested objects.

My Model entity list object = SourceObject-A;

My Model entity second object = SourceObject-B;

My Doamin entity list object = TargetObject-AB;

My source classes looks like this:

SourceObject-A:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {

  private int id;
  private String name;

  }

SourceObject-B:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class CountryDetails {

    private String country;
    private String countryCode;

}

So I need to tranform it to this(TargetObject-AB):

@NoArgsConstructor
@AllArgsConstructor
@Data
public class DomainUser {
    private int id;
    private String name;
    private String country;
    private String countryCode;
}

UserController:

GetMapping("/users")
public List<DomainUser> getDUsers(List<User> usersList, CountryDetails countryDetails){

     List<DomainUser> domainUsersList=ModelToDomainMapper.INSTANCE.UserToDUser(usersList, 
     countryDetails);


  return domainUsersList;

}

Mapper Interface:

@Mapper
public interface ModelToDomainMapper {

    ModelToDomainMapper INSTANCE = Mappers.getMapper(ModelToDomainMapper.class)


    List<DomainUser> UserToDUser(List<User> users, CountryDetails countryDetails);


}

Expected sample json:

Source(Input):

[
        
  "countryDetails":{
        
                 "country"     : "India",
                 "countryCode" : "+91"
           
                  },
  "userslist" :[
        
            {
        
                "id"   : 1,
                "name" : "XXXXXXX"
           
              },
            {
        
               "id"   : 2,
               "name" : "XXXXXXX"
           
             }
        ]
    ]

Target(Expected Output):

[
  {
    "id": 1,
    "name": "xxxxxx",
    "country": "India",
    "countryCode": "+91"
  },
  {
    "id": 2,
    "name": "xxxxxx",
    "country": "India",
    "countryCode": "+91"
  }
]

Is there any way to get this above output please help me.

1 Answers

You could do something like this in your mapper:

    DomainUser UserToDUser(User user, CountryDetails countryDetails);

    default List<DomainUser> UsersToDomainUsers(List<User> users, CountryDetails countryDetails) {
        return users.stream()
                .map((user -> UserToDUser(user, countryDetails)))
                .collect(Collectors.toList());
    }

This would use the MapStruct generated mapper to merge every single User with the same CountryDetails to create a DomainUser and collect them all into a List using streams.

Related