Search code examples
javamappingmapstruct

mapstruct, nested classes avoid writing mapper for each nested class


I have source and target classes that look like this

class UserHistorySource {
   private DetailsSource details;
}

and

class DetailsSource {

   private List<BalanceSource> balance;
   private List<RewardsSource> rewards;
   private List<LogsSource> logs;
   ….
   ….
}


class BalanceSource {

private String userId;
private OffsetDateTime datetime;
private String amount;

}


class RewardsSource {

private String userId;
private OffsetDateTime datetime;
private String amount;

}

class LogsSource {

private String userId;
private OffsetDateTime datetime;
private String amount;

}

Target Classes:

class UserHistoryTarget {
  private DetailsTarget details;
}

class DetailsTarget {

  private List<BalanceTarget> balance;
  private List<RewardsTarget> rewards;
  private List<LogsTarget> logs;
  ….
  ….
}


class BalanceTarget {

  private String userId;
  private String datetime;
  private String amount;
}


class RewardsTarget {
  private String userId;
  private String datetime;
  private String amount;
}

class LogsTarget {

  private String userId;
  private String datetime;
  private String amount;
}

The datetime in target classes are of type string while in source are of OffsetDateTime. I could potentially create indivisual mapper files for Details, Balance, Rewards and Logs and implement a default method to convert the OffsetDateTime to String but I want to avoid writting mapper files for each class, is there a better way to do this ?


Solution

  • You don't need to create mappers (or even: mapping methods) for all those classes.

    It is sufficient (if you have getters and setters for the fields) to have have the following mapper definition:

    @Mapper
    interface UserHistoryMapper {
        UserHistoryTarget map(UserHistorySource source);
    
        default String map(OffsetDateTime odt) {
            // sample implementation
            return odt.toString();
        }
    }
    

    The MapStruct annotation processor will generate the needed mapping methods and call the String map(OffsetDateTime odt) where needed.