-1

I want to map an int to string with a specific mapping, but mapstrcut always converts automatically from int to string using String.valueOf, how can i deactivated this auto mapping ?

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface SeanceMapper {

  @Mapping(target = "startHour", qualifiedByName = "toStartHour")
  SeanceDTO seanceEntityToseanceDTO(SeanceEntity seanceEntity);

  @Named("toStartHour")
  default String toStartHour(SeanceEntity seanceEntity) {
    String startHour = Integer.toString(seanceEntity.getStartHour());
    if (startHour.length() == 3) {
        startHour = "0" + startHour;
    }
    return startHour.substring(0, 2) + "H:" + startHour.substring(2, startHour.length());
  }

}

SeanceMapperImpl

@Override
public SeanceDTO seanceEntityToseanceDTO(SeanceEntity seanceEntity) {
    if ( seanceEntity == null ) {
        return null;
    }

    SeanceDTO seanceDTO = new SeanceDTO();

    seanceDTO.setStartHour( String.valueOf( seanceEntity.getStartHour() ) );

    return seanceDTO;
}
Aymen Kanzari
  • 1,765
  • 7
  • 41
  • 73

1 Answers1

1

In your example the name o mapping method is incorrect, so mapStruct cannot distinguish, what you would like to map using by default "auto-mapping" String -> Integer.

@Mapping(target = "startHour", source = "startHour", qualifiedByName = "toEndHour")
SeanceDTO seanceEntityToseanceDTO(SeanceEntity seanceEntity);

@Named("toEndHour")
default String toEndHour(int startHour) {
    String startHour = Integer.toString(startHour);
    if (startHour.length() == 3) {
        startHour = "0" + startHour;
    }
    return startHour.substring(0, 2) + "H:" + startHour.substring(2, startHour.length());
}

public class SeanceEntity {

    private int startHour;

}

public class SeanceDTO {

    private String startHour;

}

I've corrected method name in annotation @Named which is important to distinguish it by name in qualifiedByName field. Also in this scenario, you have to specify which source field you wanna map to target which suits to source and target. Let me know if it's work :)

centrumek
  • 280
  • 1
  • 5
  • 1
    Are you sure that you need the source? When the target and source are the same it is enough to specify the target only. In addition to that if you use 1.4 you will have a compilation error due to the missing qualifiedByName method – Filip Jan 20 '21 at 04:25
  • sorry, in my code the the name of mapping method is correct just when i do copy paste i copy the incorrect methode because i have two attributes startHour and endDate. I corrected my above question and i added the impl. The problem stay the same when i added the source. – Aymen Kanzari Jan 20 '21 at 06:32
  • 1
    when i upgrade my version from 1.3 to 1.4, is worked correct. – Aymen Kanzari Jan 20 '21 at 06:51
  • @Filip probably you are right, I didn't compile it. – centrumek Jan 20 '21 at 17:49