Skip to content
Advertisement

MapStruct – Can’t map property Optional to LocalDate

NOTE: This is unlike other questions on StackOverflow because they resolve this issue by mapping the two classes manually. Since ScheduleSource and ScheduleTarget are exactly the same classes, I want them to be mapped automatically.

Hi,

I have 2 classes ScheduleSource and ScheduleTarget. They have exactly the same properties.

When I try to use MapStruct to map from ScheduleSource to ScheduleTarget, I get the error:

  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)

I have attached the two files. Can you please help?

Files are:

  • ScheduleSource, ScheduleTarget – the two Java Beans
  • ScheduleMapper – the mapping class.

  • 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);
}

  • ScheduleSource.java, ScheduleTarget.java – same structure
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;
  }
}

Advertisement

Answer

I’m not familiar with mapstruct, but I can guess it maps different objects 🙂

If your source and target classes have the same structure then the problem is

public Optional<LocalDate> getStartDate();
public void setStartDate(LocalDate startDate);

So it gets the Optional object and tries to pass it to a method accepting a LocalDate.

So your possible ways of action are

  1. change getter to return a simple object
  2. change setter to accept an optional (which is fine I guess, but seems a bit off)
  3. declare a mapper method
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement