How to map Enum attribute into an Enum of another type with Mapstruct - Java

Viewed 65

I have two similar enums used respectively in Domain and Entity class. Here is an Example :

Classes

public class Entity {
   String name;
   State state;
}
public class Domain {
   String name;
   Status status;
}
public enum Status {
   PENDING,
   CANCELLED
}
public enum State {
   PENDING,
   CANCELLED
}

Mappers

public interface StatusMapper {
   public Status statusToState(Status status);
}
public interface EntityMapper {
   public Domain EntityToDomain(Entity entity);
}

What do I have to do if I want to know how to map Entity to Domain so that :

Entity { name: "Name", state: "PENDING" } 

becomes and maps into :

Domain { name: "Name", status: "PENDING" }

You can see here that State and Status are the same. I have tested it but status becomes null when mapping Entity to Domain.

Thanks for your answers.

1 Answers

You can get rid of StatusMapper and instead of EntityMapper you can using the following interface.

import com.package.domain.Domain;
import com.package.entity.Entity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.core.convert.converter.Converter;

@Mapper(componentModel = "spring")
public interface EntityToDomainConverter extends Converter<Entity, Domain> {

    @Mapping(source = "state", target = "status")
    Domain convert(Entity source);
}

The generated class will look like

import com.package.domain.Domain;
import com.package.entity.Entity;
import com.package.State;
import com.package.Status;
import javax.annotation.Generated;
import org.springframework.stereotype.Component;

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2022-06-30TXX:XX:XX+YYYY",
    comments = "version: 1.4.2.Final, compiler: javac, environment: Java 16.0.2 (Homebrew)"
)
@Component
public class EntityToDomainConverterImpl implements EntityToDomainConverter {

    @Override
    public Domain convert(Entity source) {
        if ( source == null ) {
            return null;
        }

        Domain domain = new Domain();

        domain.setStatus( stateToStatus( source.getState() ) );
        domain.setName( source.getName() );

        return domain;
    }

    protected Status stateToStatus(State state) {
        if ( state == null ) {
            return null;
        }

        Status status;

        switch ( state ) {
            case PENDING: status = Status.PENDING;
            break;
            case CANCELLED: status = Status.CANCELLED;
            break;
            default: throw new IllegalArgumentException( "Unexpected enum constant: " + state );
        }

        return status;
    }
}
Related