这可以通过多种方式完成。下面你会看到 2 个选项。他们做同样的事情只有一个使用qualifiedByName,而另一个使用expression。根据您的需要,一个可能比另一个更适合。
使用 mapstruct 找到的自定义方法
qualifiedByName 是必需的,否则 mapstruct 不知道使用哪种方法。
@Mapping(source = ".", target = "startTime", qualifiedByName = "startTime")
@Mapping(source = ".", target = "endTime", qualifiedByName = "endTime")
AvailabilityRuleDTO toAvailabilityRuleDTO(AvailabilityRule availabilityRule, @Context Schedule schedule);
@Named("startTime")
protected ZonedDateTime startTime(AvailabilityRule availabilityRule, @Context Schedule schedule) {
return convertTime(availabilityRule.startEpoch, schedule.timezoneId);
}
@Named("endTime")
protected ZonedDateTime endTime(AvailabilityRule availabilityRule, @Context Schedule schedule) {
return convertTime(availabilityRule.endEpoch, schedule.timezoneId);
}
private ZonedDateTime convertTime(long epoch, String timezoneId) {
Instant instant = Instant.ofEpochMilli(epoch);
ZonedDateTime time = LocalDateTime.from(instant).atZone(timezoneId);
return time;
}
使用由表达式配置的自定义方法
@Named 在这里使用是为了防止 mapstruct 不小心将此方法用于其他映射操作。没有它,它很可能仍然可以工作。
@Mapping(target = "startTime", expression = "java(convertTime(availabilityRule.startEpoch, schedule.timezoneId))" )
@Mapping(target = "endTime", expression = "java(convertTime(availabilityRule.endEpoch, schedule.timezoneId))" )
AvailabilityRuleDTO toAvailabilityRuleDTO(AvailabilityRule
availabilityRule, Schedule schedule);
@Named("time")
protected ZonedDateTime convertTime(long epoch, String timezoneId) {
Instant instant = Instant.ofEpochMilli(epoch);
ZonedDateTime time = LocalDateTime.from(instant).atZone(timezoneId);
return time;
}
完整的映射器,包括时间表
@Mapper
public abstract class ScheduleMapper {
@Mapping(target = "timezone", source = "timezoneId")
@Mapping(target = "rules", expression = "java(toAvailabilityRuleDTOs(schedule.getRules(), schedule))")
abstract ScheduleDTO toScheduleDTO(Schedule schedule);
@Named("rules")
abstract List<AvailabilityRuleDTO> toAvailabilityRuleDTOs(List<AvailabilityRule> rules, @Context Schedule schedule);
@Mapping(target = "startTime", expression = "java(convertTime(availabilityRule.startEpoch, schedule.timezoneId))")
@Mapping(target = "endTime", expression = "java(convertTime(availabilityRule.endEpoch, schedule.timezoneId))")
abstract AvailabilityRuleDTO toAvailabilityRuleDTO(AvailabilityRule availabilityRule, @Context Schedule schedule);
@Named("time")
protected ZonedDateTime convertTime(long epoch, ZoneId timezoneId) {
Instant instant = Instant.ofEpochMilli(epoch);
ZonedDateTime time = LocalDateTime.from(instant).atZone(timezoneId);
return time;
}
String map(ZoneId zoneId) {
return zoneId == null ? null : zoneId.getId();
}
}