简体   繁体   中英

Boolean defaultValue MapStruct

I'm trying to set a defaultValue for a boolean field using MapStruct, but the generated code simply ignores it.

My code:

public class CreateEventRequest {

    @NotNull
    @JsonProperty
    private Boolean isPrivate;

    @JsonProperty
    private Boolean friendCanInviteFriends;

    @JsonProperty
    private boolean showGuestList;

    public boolean isPrivate() {
      return isPrivate;
     }

     public String getDescription() {
       return description;
     }

      public boolean isFriendCanInviteFriends() {
        return friendCanInviteFriends;
     }

      public boolean isShowGuestList() {
        return showGuestList;
     }
}

My mapper:

@Mapper(componentModel = "spring")
public interface CreateEventRequestMapper {
    @Mapping(target = "showGuestList", source = "showGuestList", defaultExpression = "java(true)")
    @Mapping(target = "friendCanInviteFriends", source = "friendCanInviteFriends", defaultValue = "true")
    Event map(CreateEventRequest request);
}

The generated code:

public class CreateEventRequestMapperImpl implements CreateEventRequestMapper {

    @Override
    public Event map(CreateEventRequest request) {
        if ( request == null ) {
            return null;
        }

        Event event = new Event();

        event.setShowGuestList( request.isShowGuestList() );
        event.setFriendCanInviteFriends( request.isFriendCanInviteFriends() );
        event.setPrivate( request.isPrivate() );

        return event;
    }
}

As you can see, I've tried using primitive/non-primitive type but it simply ignores the defaultValue.

Am I missing something here?

Thanks!

The problem is that the return type of your getter methods in the source object is always primitive which can't be null, you need to return Boolean .

MapStruct doesn't support direct private field access which requires reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM