weblog

技術的なメモ置き場。

【MapStruct】暗黙的な型変換

今回は暗黙的な型変換についてまとめる。 異なる型のフィールドにマッピングする際に暗黙的な型変換が行われる。

環境

  • MapStruct : 1.2.0.Final
  • Java : 9
  • JUnit : 4.12
  • AssertJ : 3.9.1

使用するBean

public class Dto {
    private int intValue;
    private long longValue;
    private double doubleValue;
    private boolean boolValue;
    private LocalDate localDateValue;
    // constructor/setter/getter
}

public class ConvertDto {
    private String intValue;
    private String longValue;
    private String doubleValue;
    private String boolValue;
    private String localDateValue;
    // constructor/setter/getter
}

プリミティブ型 -> String型

プリミティブ型(ラッパーも含む)はString型に変換される。

@Mapper
public interface ImplicitTypeConvertMapper {
    ImplicitTypeConvertMapper MAPPER = Mappers.getMapper(ImplicitTypeConvertMapper.class);

    ConvertDto toConvertDto(Dto dto);
}

テストコード

@Test
public void test() {
    Dto dto = new Dto();
    dto.setIntValue(1);
    dto.setLongValue(100L);
    dto.setDoubleValue(30.5);
    dto.setBoolValue(true);

    ConvertDto convertDto = ImplicitTypeConvertMapper.MAPPER.toConvertDto(dto);

    Assertions.assertThat(convertDto.getIntValue()).isEqualTo("1");
    Assertions.assertThat(convertDto.getLongValue()).isEqualTo("100");
    Assertions.assertThat(convertDto.getDoubleValue()).isEqualTo("30.5");
    Assertions.assertThat(convertDto.getBoolValue()).isEqualTo("true");

}

数値, 日付のフォーマット

数値や日付はフォーマットしてマッピングすることができる。 numberFormat dateFormat にフォーマットを指定する。

@Mapper
public interface ImplicitTypeConvertMapper {

    ImplicitTypeConvertMapper MAPPER = Mappers.getMapper(ImplicitTypeConvertMapper.class);

    @Mapping(target = "intValue", numberFormat = "000")
    @Mapping(target = "localDateValue", dateFormat = "yyyy/MM/dd")
    ConvertDto format(Dto dto);
}

テストコード

@Test
public void test() {
    Dto dto = new Dto();
    dto.setIntValue(1);
    dto.setLocalDateValue(LocalDate.of(2020, 1, 20));

    ConvertDto convertDto = ImplicitTypeConvertMapper.MAPPER.format(dto);

    assertThat(convertDto.getIntValue()).isEqualTo("001");
    assertThat(convertDto.getLocalDateValue()).isEqualTo("2020/01/20");
}

他にも型変換の組み合わせがあるので、公式ドキュメントを参考。 http://mapstruct.org/documentation/stable/reference/html/#implicit-type-conversions