注意:这与StackOverflow上的其他问题不同,因为它们通过手动映射两个类来解决此问题。由于ScheduleSource和ScheduleTarget是完全相同的类,因此我希望将它们自动映射。
嗨,
我有2个类ScheduleSource和ScheduleTarget。它们具有完全相同的属性。
当我尝试使用MapStruct从ScheduleSource映射到ScheduleTarget时,出现错误:
Can't map property "java.util.Optional<java.time.LocalDate> startDate" to "java.time.LocalDate startDate". Consider to declare/implement a mapping method: "java.time.LocalDate map(java.util.Optional<java.time.LocalDate> value)
我已经附上了两个文件。你能帮忙吗?
文件为:
ScheduleMapper-映射类。
ScheduleMapper.java
package testStructMap; import org.mapstruct.*; import org.mapstruct.factory.*; @Mapper public interface ScheduleMapper { ScheduleMapper INSTANCE = Mappers.getMapper( ScheduleMapper.class ); ScheduleTarget scheduleSourceToScheduleTarget(ScheduleSource scheduleSource); }
package testStructMap; import java.time.LocalDate; import java.time.LocalTime; import java.util.Optional; import javax.validation.constraints.*; public class ScheduleSource { @FutureOrPresent @NotNull private LocalDate startDate; @NotBlank private String repeatType; @Positive private Integer occurrences; public Optional<LocalDate> getStartDate() { return Optional.ofNullable(startDate); } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public String getRepeatType() { return repeatType; } public void setRepeatType(String repeatType) { this.repeatType = repeatType; } public Optional<Integer> getOccurrences() { return Optional.ofNullable(occurrences); } public void setOccurrences(Integer occurrences) { this.occurrences = occurrences; } }
答案 0 :(得分:2)
我不熟悉mapstruct,但是我可以猜到它映射了不同的对象:)
如果您的源类和目标类具有相同的结构,那么问题就出在
public Optional<LocalDate> getStartDate();
public void setStartDate(LocalDate startDate);
因此,它获取Optional对象,并尝试将其传递给接受LocalDate的方法。
所以您可能的应对方式是
答案 1 :(得分:1)
在1.3.0.beta1中,支持以下功能:
package testStructMap;
import org.mapstruct.*;
import org.mapstruct.factory.*;
@Mapper
public interface ScheduleMapper {
ScheduleMapper INSTANCE = Mappers.getMapper( ScheduleMapper.class );
ScheduleTarget scheduleSourceToScheduleTarget(ScheduleSource scheduleSource);
default <T> T unwrapOptional(Optional<T> optional) {
return optional.orElse(null);
}
}
答案 2 :(得分:0)
映射目标可选对源,而不是可选我们如何使它遵循以下示例:
@Named("HelperClass")
class Helper {
@Named("convertToOptional")
public Optional<KontaktpersonVerwandtschaftsgradTyp> convertToOptional(KontaktpersonVerwandtschaftsgradTyp optional) {
return optional != null ? Optional.of(optional) : Optional.empty();
};
}
@Mapping(target = "kontaktpersonVerwandtschaftsgrad", source = "tdfFall.kontaktpersonVerwandtschaftsgrad", qualifiedByName = { "HelperClass",
"convertToOptional" })
,我们还需要添加用途和Helper类的名称
@Mapper(componentModel = "spring", uses = { Helper.class })