使用Mapstruct将多个源字段映射到相同类型的目标字段

时间:2016-06-08 14:30:38

标签: java mapping mapstruct

考虑以下POJO:

'.*?(?<!\\)'     # look for a single quote up to a new single quote
                 # that MUST NOT be escaped (thus the neg. lookbehind)
(*SKIP)(*FAIL)|  # these parts shall fail
(?<=\)),(?=\()   # your initial pattern with a positive lookbehind/ahead

使用MapStruct,我创建了一个将public class SchedulePayload { public String name; public String scheduler; public PeriodPayload notificationPeriod; public PeriodPayload schedulePeriod; } private class Lecture { public ZonedDateTime start; public ZonedDateTime end; } public class XmlSchedule { public String scheduleName; public String schedulerName; public DateTime notificationFrom; public DateTime notificationTo; public DateTime scheduleFrom; public DateTime scheduleTo; } public class PeriodPayload { public DateTime start; public DateTime finish; } 映射到XmlSchedule的映射器。由于“业务”“逻辑”,我需要将SchedulePayloadnotificationPeriod限制为schedulePeriod的{​​{1}}和Lecture字段值。以下是我所使用的另一个课程:

start

有没有办法可以通过其他方式实现(即另一个映射器,装饰器等)?如何将多个值(xmlSchedule,讲座)传递给映射器?

1 个答案:

答案 0 :(得分:8)

您可以做的是创建一个@AfterMapping方法来手动填充这些部分:

@Mapper
public abstract class SchedulePayloadMapper
{
    @Mappings({
        @Mapping(target = "name", source = "scheduleName"),
        @Mapping(target = "scheduler", source = "schedulerName"),
        @Mapping(target = "notificationPeriod", expression = "java(NotificationPeriodHelper.getConstrainedPeriod(xmlSchedule, notificationFrom, notificationTo))"),
        @Mapping(target = "schedulePeriod", expression = "java(NotificationPeriodHelper.getConstrainedPeriod(xmlSchedule, scheduleFrom, scheduleTo))")
    })
    public abstract SchedulePayload map(XmlSchedule xmlSchedule, Lecture lecture);

    @AfterMapping
    protected void addPeriods(@MappingTarget SchedulePayload result, XmlSchedule xmlSchedule, Lecture lecture) {
        result.setNotificationPeriod(..);
        result.setSchedulePeriod(..);
    }
}

或者,您可以将@AfterMapping方法放在@Mapper(uses = ..)中引用的另一个类中,也可以使用Decorator(使用MapStruct提供的机制,或者使用依赖注入框架) )。