Search code examples
javamapstruct

mapstruct: map field to single string value (return value)


Here my mapper:

@Mapper
public interface DocumentMapper {

    @Mapping(source = "uuid", target = "id")
    net.gencat.transversal.espaidoc.domain.model.document.DocumentId toDomainModel(String uuid);

    @InheritInverseConfiguration
    String toPersistenceModel(net.gencat.transversal.espaidoc.domain.model.document.DocumentId id);

}

net.gencat.transversal.espaidoc.domain.model.document.DocumentId class is:

package net.gencat.transversal.espaidoc.domain.model.document;

import java.util.UUID;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;

@Getter
@AllArgsConstructor
@EqualsAndHashCode
@ToString
@Builder
public class DocumentId {

    private final UUID id;

}

As you can see, I'm trying to map from "DocumentId.id" to String.

MapStruct is generating well toDomainModel, but it's failing on toPersistenceModel:

    @Override
    public DocumentId toDomainModel(String uuid) {
        if ( uuid == null ) {
            return null;
        }

        DocumentId.DocumentIdBuilder documentId = DocumentId.builder();

        if ( uuid != null ) {
            documentId.id( UUID.fromString( uuid ) );
        }

        return documentId.build();
    }

    @Override
    public String toPersistenceModel(DocumentId id) {
        if ( id == null ) {
            return null;
        }

        String string = new String();

        return string;
    }

How could I tell to mapstruct to map correctly from DocumentId.id to single value?

Any ideas?


Solution

  • MapStruct does not support extracting values from a source object and returning them. It always try to map from one object into another object. In order to achieve what you are looking for you'll need to write your own custom method for that.

    e.g.

    @Mapper
    public interface DocumentMapper {
    
        @Mapping(source = "uuid", target = "id")
        net.gencat.transversal.espaidoc.domain.model.document.DocumentId toDomainModel(String uuid);
    
        default String toPersistenceModel(net.gencat.transversal.espaidoc.domain.model.document.DocumentId id) {
            if (id == null) {
                return null;
            }
            UUID uuid = id.getId();
            return uuid != null ? uuid.toString() : null;
        }
    
    }